utilities.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. #fool: should be wrColor like prColor... dumb
  2. def wrapRed(skk): return "\033[91m{}\033[00m".format(skk)
  3. def wrapGreen(skk): return "\033[92m{}\033[00m".format(skk)
  4. def wrapPurple(skk): return "\033[95m{}\033[00m".format(skk)
  5. def wrapWhite(skk): return "\033[97m{}\033[00m".format(skk)
  6. def wrapOrange(skk): return "\033[0;33m{}\033[00m".format(skk)
  7. # these should reimplement the print interface..
  8. def prRed(*args): print (*[wrapRed(arg) for arg in args])
  9. def prGreen(*args): print (*[wrapGreen(arg) for arg in args])
  10. def prPurple(*args): print (*[wrapPurple(arg) for arg in args])
  11. def prWhite(*args): print (*[wrapWhite(arg) for arg in args])
  12. def prOrange(*args): print (*[wrapOrange(arg) for arg in args])
  13. # add THIS to the top of a file for easy access:
  14. # from mantis.utilities import (prRed, prGreen, prPurple, prWhite,
  15. # prOrange,
  16. # wrapRed, wrapGreen, wrapPurple, wrapWhite,
  17. # wrapOrange,)
  18. def float_lerp(a : float, b : float, factor : float) -> float:
  19. return (a * (1.0 - factor)) + (b * factor)
  20. # A fuction for getting to the end of a Reroute.
  21. # TODO: this seems really inefficient!
  22. def socket_seek(start_link, links):
  23. link = start_link
  24. while(link.from_socket):
  25. for newlink in links:
  26. if link.from_socket.node.inputs:
  27. if link.from_node.bl_idname != 'NodeReroute':
  28. return link.from_socket
  29. if newlink.to_socket == link.from_socket.node.inputs[0]:
  30. link=newlink; break
  31. else:
  32. break
  33. return link.from_socket
  34. # THIS ONE is better. I don't know what I was thinking up above.
  35. # TODO: try and refactor to use this function instead
  36. def find_reroute_start_socket(reroute, track='BACK'):
  37. # "BACK" traces back through the tree
  38. # "FORWARD" traces forward through the tree
  39. socket = None
  40. while (reroute and track == 'BACK'):
  41. if len(reroute.inputs[0].links) == 1:
  42. link = reroute.inputs[0].links[0]
  43. socket = link.from_socket
  44. if link.from_node.bl_idname == 'NodeReroute':
  45. reroute = link.from_node
  46. else:
  47. link, reroute = None, None
  48. while (reroute and track == 'FORWARD'):
  49. if len(reroute.outputs[0].links) == 1:
  50. link = reroute.outputs[0].links[0]
  51. socket = link.to_socket
  52. if link.to_node.bl_idname == 'NodeReroute':
  53. reroute = link.to_node
  54. else:
  55. link, reroute = None, None
  56. return socket
  57. # this creates fake links that have the same interface as Blender's
  58. # so that I can bypass Reroutes
  59. def clear_reroutes(links):
  60. from .base_definitions import DummyLink
  61. kept_links, rerouted_starts = [], []
  62. rerouted = []
  63. all_links = links.copy()
  64. while(all_links):
  65. link = all_links.pop()
  66. to_cls = link.to_socket.node.bl_idname
  67. from_cls = link.from_socket.node.bl_idname
  68. reroute_classes = ["NodeReroute"]
  69. if (to_cls in reroute_classes and
  70. from_cls in reroute_classes):
  71. rerouted.append(link)
  72. elif (to_cls in reroute_classes and not
  73. from_cls in reroute_classes):
  74. rerouted.append(link)
  75. elif (from_cls in reroute_classes and not
  76. to_cls in reroute_classes):
  77. rerouted_starts.append(link)
  78. else:
  79. kept_links.append(link)
  80. for start in rerouted_starts:
  81. from_socket = socket_seek(start, rerouted)
  82. new_link = DummyLink(from_socket=from_socket, to_socket=start.to_socket, nc_from=None, nc_to=None, multi_input_sort_id=start.multi_input_sort_id )
  83. kept_links.append(new_link)
  84. return kept_links
  85. def tree_from_nc(sig, base_tree):
  86. if (sig[0] == 'MANTIS_AUTOGENERATED'):
  87. sig = sig[:-2] # cut off the end part of the signature (because it uses socket.name and socket.identifier)
  88. # this will lead to totally untraceble bugs in the event of a change in how signatures are assigned
  89. tree = base_tree
  90. for i, path_item in enumerate(sig):
  91. if (i == 0) or (i == len(sig) - 1):
  92. continue
  93. tree = tree.nodes.get(path_item).node_tree
  94. return tree
  95. def get_node_prototype(sig, base_tree):
  96. return tree_from_nc(sig, base_tree).nodes.get( sig[-1] )
  97. ##################################################################################################
  98. # groups and changing sockets -- this is used extensively by Schema.
  99. ##################################################################################################
  100. # this one returns None if there is an error.
  101. def get_socket_maps(node, force=False):
  102. maps = [{}, {}]
  103. node_collection = ["inputs", "outputs"]
  104. links = ["from_socket", "to_socket"]
  105. for collection, map, linked_socket in zip(node_collection, maps, links):
  106. for sock in getattr(node, collection):
  107. if sock.is_linked:
  108. other_sockets = []
  109. # Sort the links first (in case they are mult-input), because Blender doesn't
  110. links = sorted(list(sock.links), key = lambda l : l.multi_input_sort_id)
  111. # HACK here because Blender will crash if the socket values in the NodeReroute
  112. # are mutated. Because this seems to happen in a deffered way, I can't account
  113. # for it except by checking the node later...
  114. # TODO: The fact that I need this hack means I can probably solve this problem
  115. # for all node types in a safer way, since they may also be dynamic somehow
  116. for l in links:
  117. if "from" in linked_socket and l.from_node.bl_idname == "NodeReroute":
  118. other_sockets.append(l.from_node)
  119. elif "to" in linked_socket and l.to_node.bl_idname == "NodeReroute":
  120. other_sockets.append(l.to_node)
  121. else:
  122. other_sockets.append(getattr(l, linked_socket))
  123. from bpy.types import NodeSocket
  124. keep_sockets=[]
  125. for other_socket in other_sockets.copy():
  126. if isinstance(other_socket, NodeSocket) and \
  127. other_socket.bl_idname == 'NodeSocketUndefined':
  128. continue # this one is bad
  129. keep_sockets.append(other_socket)
  130. # if len(keep_sockets) == 0:
  131. # keep_sockets = None
  132. map[sock.identifier]= keep_sockets
  133. elif hasattr(sock, "default_value"):
  134. if sock.get("default_value") is not None:
  135. val = sock['default_value']
  136. elif sock.bl_idname == "EnumCurveSocket" and sock.get("default_value") is None:
  137. # HACK I need to add this special case because during file-load,
  138. # this value is None and should not be altered until it is set once.
  139. continue
  140. elif "Enum" in sock.bl_idname and isinstance(sock.get("default_value"), int):
  141. continue # for string enum properties that have not yet initialized (at startup)
  142. elif (val := sock.default_value) is not None:
  143. pass
  144. elif not force:
  145. continue
  146. map[sock.identifier]=val
  147. else:
  148. from .socket_definitions import no_default_value
  149. if sock.bl_idname in no_default_value:
  150. map[sock.identifier]=None
  151. else:
  152. raise RuntimeError(f"ERROR: Could not get socket data for socket of type: {sock.bl_idname}")
  153. return maps
  154. # this function is completely overloaded with different purposes and code paths
  155. # TODO refactor everything that funnels into this function
  156. # make this stuff simpler.
  157. def do_relink(node, socket, map, in_out='INPUT', parent_name = ''):
  158. if not node.__class__.is_registered_node_type(): return
  159. tree = node.id_data; interface_in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT'
  160. if hasattr(node, "node_tree"):
  161. tree = node.node_tree
  162. interface_in_out=in_out
  163. from bpy.types import NodeSocket, Node
  164. get_string = '__extend__'
  165. if socket: get_string = socket.identifier
  166. from .base_definitions import SchemaUINode
  167. if (hasattr(node, "node_tree") or isinstance(node, SchemaUINode)) and get_string not in map.keys():
  168. # this happens when we are creating a new node group and need to update it from nothing.
  169. return
  170. val = map[get_string] # this will throw an error if the socket isn't there. Good!
  171. if isinstance(val, list):
  172. for sub_val in val:
  173. # this will only happen once because it assigns socket, so it is safe to do in the for loop.
  174. if socket is None:
  175. socket = sub_val
  176. if sub_val.bl_idname == "NodeReroute":
  177. # we have to trace the reroute node...
  178. if in_out == 'INPUT':
  179. socket = find_reroute_start_socket(sub_val)
  180. else:
  181. socket = find_reroute_start_socket(sub_val, track="FORWARD")
  182. sock_type = socket.interface_type
  183. name = unique_socket_name(node, socket, tree)
  184. if parent_name:
  185. interface_socket = update_interface(tree.interface, name, interface_in_out, sock_type, parent_name)
  186. if in_out =='INPUT':
  187. socket = node.inputs.new(sock_type, name, identifier=interface_socket.identifier)
  188. else:
  189. socket = node.outputs.new(sock_type, name, identifier=interface_socket.identifier)
  190. if parent_name == 'Array': socket.display_shape='SQUARE_DOT'
  191. if parent_name == 'Constant': socket.display_shape='CIRCLE_DOT'
  192. # then move it up and delete the other link.
  193. # this also needs to modify the interface of the node tree.
  194. if isinstance(sub_val, NodeSocket):
  195. l = None
  196. if in_out =='INPUT':
  197. l = node.id_data.links.new(input=sub_val, output=socket)
  198. else:
  199. l = node.id_data.links.new(input=socket, output=sub_val)
  200. if l is None:
  201. raise RuntimeError("Could not create link")
  202. elif isinstance(sub_val, Node):
  203. l = None
  204. # this happens when it is a NodeReroute
  205. if not socket.is_output:
  206. l = node.id_data.links.new(input=sub_val.outputs[0], output=socket)
  207. else:
  208. l = node.id_data.links.new(input=socket, output=sub_val.inputs[0])
  209. if l is None:
  210. raise RuntimeError("Could not create link")
  211. else:
  212. raise RuntimeError("Unhandled case in do_relink()")
  213. elif get_string != "__extend__":
  214. if not socket.is_output:
  215. from bpy.app import version as bpy_version
  216. if bpy_version >=(4,5,0): # VERSIONING
  217. # for some reason, this is throwing an error now
  218. from bpy.types import bpy_prop_array
  219. if isinstance(val, bpy_prop_array):
  220. if in_out == "INPUT" and hasattr(socket, 'input') and socket.input == False:
  221. return # doesn't matter, this is a Matrix socket in a bone or something
  222. # raise RuntimeError(
  223. # f"Cannot set property in socket of type {socket.bl_idname} due to bug in Blender: "
  224. # f"{node.id_data.name}:{node.name}:{socket.name} ")
  225. # TODO: report this weird bug!
  226. try:
  227. if socket.bl_idname == 'BooleanThreeTupleSocket':
  228. # it is so annoying that I have to do this
  229. socket.default_value = [bool(val[0]), bool(val[1]), bool(val[2])]
  230. else:
  231. socket.default_value = val
  232. except (AttributeError, ValueError): # must be readonly or maybe it doesn't have a d.v.
  233. pass
  234. def update_interface(interface, name, in_out, sock_type, parent_name):
  235. from bpy.app import version as bpy_version
  236. if parent_name:
  237. if not (interface_parent := interface.items_tree.get(parent_name)):
  238. interface_parent = interface.new_panel(name=parent_name)
  239. if bpy_version != (4,5,0):
  240. socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  241. else: # blender 4.5.0 LTS, have to workaround a bug!
  242. from .versioning import workaround_4_5_0_interface_update
  243. socket = workaround_4_5_0_interface_update(tree=interface.id_data, name=name, in_out=in_out,
  244. sock_type=sock_type, parent_name=parent_name, do_parent=True)
  245. if parent_name == 'Connection':
  246. in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT' # flip this make sure connections always do both
  247. interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  248. return socket
  249. else:
  250. raise RuntimeError(wrapRed("Cannot add interface item to tree without specifying type."))
  251. # D.node_groups['Rigging Nodes'].interface.new_socket('beans', description='the b word', socket_type='NodeSocketGeometry')
  252. #UGLY BAD REFACTOR
  253. def relink_socket_map_add_socket(node, socket_collection, item, in_out=None,):
  254. from bpy.app import version as bpy_version
  255. if not in_out: in_out=item.in_out
  256. if node.bl_idname in ['MantisSchemaGroup'] and item.parent and item.parent.name == 'Array':
  257. multi = True if in_out == 'INPUT' else False
  258. # have to work around a bug in 4.5.0 that prevents me from declaring custom socket types
  259. # I have arbitrarily chosen to use the NodeSocketGeometry type to signal that this one is affected.
  260. if bpy_version == (4, 5, 0) and item.bl_socket_idname == 'NodeSocketGeometry':
  261. from .versioning import socket_add_workaround_for_4_5_0_LTS
  262. s = socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi)
  263. else:
  264. s = socket_collection.new(type=item.bl_socket_idname, name=item.name, identifier=item.identifier, use_multi_input=multi)
  265. else:
  266. if bpy_version == (4, 5, 0) and item.bl_socket_idname == 'NodeSocketGeometry':
  267. from .versioning import socket_add_workaround_for_4_5_0_LTS
  268. s = socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi=False,)
  269. else:
  270. s = socket_collection.new(type=item.bl_socket_idname, name=item.name, identifier=item.identifier)
  271. if item.parent.name == 'Array': s.display_shape = 'SQUARE_DOT'
  272. elif item.parent.name == 'Constant': s.display_shape='CIRCLE_DOT'
  273. return s
  274. # TODO REFACTOR THIS
  275. # I did this awful thing because I needed the above code
  276. # but I have provided this interface to Mantis
  277. # I did not follow the Single Responsibility Principle
  278. # I am now suffering for it, as I rightly deserve.
  279. def relink_socket_map(node, socket_collection, map, item, in_out=None,):
  280. s = relink_socket_map_add_socket(node, socket_collection, item, in_out=None,)
  281. do_relink(node, s, map)
  282. def unique_socket_name(node, other_socket, tree):
  283. name_stem = other_socket.bl_label; num=0
  284. # if hasattr(other_socket, "default_value"):
  285. # name_stem = type(other_socket.default_value).__name__
  286. for item in tree.interface.items_tree:
  287. if item.item_type == 'PANEL': continue
  288. if other_socket.is_output and item.in_out == 'INPUT': continue
  289. if not other_socket.is_output and item.in_out == 'OUTPUT': continue
  290. if name_stem in item.name: num+=1
  291. name = name_stem + '.' + str(num).zfill(3)
  292. return name
  293. ##############################
  294. # Dealing with Objects
  295. ##############################
  296. # use this to ensure the active object is set back when changing it
  297. def preserve_active_object(func):
  298. def wrapper(*args, **kwargs):
  299. import bpy
  300. original_active = bpy.context.active_object
  301. func(*args, **kwargs)
  302. bpy.context.view_layer.objects.active = original_active
  303. return wrapper
  304. def switch_mode(mode='OBJECT', objects = []):
  305. active = None
  306. if objects:
  307. from bpy import context, ops
  308. active = objects[-1]
  309. context.view_layer.objects.active = active
  310. if (active):
  311. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  312. ops.object.mode_set(mode=mode)
  313. return active
  314. # run this in Object mode, during bFinalize
  315. @preserve_active_object
  316. def bind_modifier_operator(modifier, operator):
  317. # now we have to bind it
  318. ob = modifier.id_data
  319. ob.modifiers.active = modifier
  320. import bpy
  321. bpy.context.view_layer.objects.active = ob
  322. # Context override does not do anything here... it isn't handled in the C code
  323. # I have verified this by building Blender with print statements to debug.
  324. # let's just make sure the target object has its modifiers disabled and update the dg
  325. targ_attr = "target"
  326. if hasattr(modifier, "object"): targ_attr = "object"
  327. target = getattr(modifier, targ_attr)
  328. if target:
  329. prWhite(f"Binding Deformer {modifier.name} to target {target.name}")
  330. operator(modifier=modifier.name)
  331. def get_default_collection(collection_type='WIDGET'):
  332. from .preferences import get_bl_addon_object
  333. from bpy import data, context
  334. mantis_addon = get_bl_addon_object(raise_error=True)
  335. match collection_type:
  336. case "WIDGET":
  337. default_collection_name=mantis_addon.preferences.WidgetDefaultCollection
  338. case "CURVE":
  339. default_collection_name=mantis_addon.preferences.CurveDefaultCollection
  340. case "ARMATURE":
  341. default_collection_name=mantis_addon.preferences.MetaArmatureDefaultCollection
  342. if default_collection_name:
  343. if not (default_collection := data.collections.get(default_collection_name)):
  344. default_collection = data.collections.new(default_collection_name)
  345. context.scene.collection.children.link(default_collection)
  346. collection = default_collection
  347. else: collection = context.collection
  348. return collection
  349. def import_widget_obj(path,):
  350. from bpy.app import version as bpy_version
  351. from bpy import context, data
  352. from os import path as os_path
  353. file_name = os_path.split(path)[-1]
  354. obj_name = os_path.splitext(file_name)[0]
  355. collection = get_default_collection(collection_type='WIDGET')
  356. if bpy_version < (4,5,0):
  357. original_active = context.active_object
  358. # for blender versions prior to 4.5.0, we have to import with an operator
  359. from bpy.ops import wm as wm_ops
  360. ob_names_before = data.objects.keys()
  361. wm_ops.obj_import(
  362. filepath=path,
  363. check_existing=False,
  364. forward_axis='NEGATIVE_Z',
  365. up_axis='Y',
  366. validate_meshes=True,)
  367. # just make sure the active object doesn't change
  368. context.view_layer.objects.active = original_active
  369. # the below is a HACK... I can find the objects in the .obj file
  370. # by scanning the file for the "o" prefix and checking the name.
  371. # but that may be slow if the obj is big. which would make a bad widget!
  372. ob = None
  373. for ob in data.objects:
  374. if ob.name in ob_names_before: continue
  375. # this is easier than setting the active collection before import.
  376. for other_collection in ob.users_collection:
  377. other_collection.objects.unlink(ob)
  378. from math import pi as PI
  379. from mathutils import Matrix
  380. m = ob.data
  381. for v in m.vertices:
  382. v.co = Matrix.Rotation(PI/2, 4, 'X') @ v.co
  383. collection.objects.link(ob)
  384. return ob # return the first one, that should be the one
  385. else: # no new object was found - fail.
  386. # I don't expect this to happen unless there is an error in the operator.
  387. raise RuntimeError(f"Failed to import {file_name}. This is probably"
  388. "a bug or a corrupted file.")
  389. else:
  390. prWhite(f"INFO: using Geometry Nodes to import {file_name}")
  391. mesh = data.meshes.new(obj_name)
  392. ob = data.objects.new(name=obj_name, object_data=mesh)
  393. # we'll do a geometry nodes import
  394. collection.objects.link(ob)
  395. if (import_modifier := ob.modifiers.get("Import OBJ")) is None:
  396. import_modifier = ob.modifiers.new("Import OBJ", type='NODES')
  397. ng = data.node_groups.get("Import OBJ")
  398. if ng is None:
  399. from .geometry_node_graphgen import gen_import_obj_node_group
  400. ng = gen_import_obj_node_group()
  401. import_modifier.node_group = ng
  402. import_modifier["Socket_0"]=path
  403. return ob
  404. def import_object_from_file(path):
  405. # first let's check to see if we need it.
  406. from os import path as os_path
  407. file_name = os_path.split(path)[-1]
  408. obj_name = os_path.splitext(file_name)[0]
  409. extension = os_path.splitext(file_name)[1]
  410. if extension == '.obj':
  411. return import_widget_obj(path,)
  412. else:
  413. raise RuntimeError(f"Failed to parse filename {path}")
  414. def import_metarig_data(metarig_data : dict, ):
  415. from bpy import data, context
  416. from mathutils import Matrix
  417. from collections import deque
  418. # the metarig data is a dict with a bunch of nodes in it
  419. # start at node 'MANTIS_RESERVED'
  420. armature_data = metarig_data['MANTIS_RESERVED']
  421. children = deque(armature_data["children"].copy())
  422. if (armature := data.armatures.get(armature_data['name'])) is None:
  423. armature = data.armatures.new(armature_data['name'])
  424. # if we need to do anything here...
  425. if (armature_object := data.objects.get(armature_data['name'])) is None:
  426. armature_object = data.objects.new(armature_data['name'], object_data=armature)
  427. armature_object.matrix_world = Matrix(
  428. ( armature_data['matrix'][:4],
  429. armature_data['matrix'][4:8],
  430. armature_data['matrix'][8:12],
  431. armature_data['matrix'][12:16], )
  432. )
  433. prGreen (armature_data['name'])
  434. # have to add it to the view layer to switch modes.
  435. collection = get_default_collection(collection_type="ARMATURE")
  436. collection.objects.link(armature_object)
  437. # we'll do this to ensure it is actually in the scene for the mode switch
  438. context.scene.collection.objects.link(armature_object)
  439. switch_mode('EDIT', objects = [armature_object])
  440. while (children):
  441. child_name = children.pop()
  442. child_data = metarig_data[child_name]
  443. eb = armature.edit_bones.new(name=child_data['name'])
  444. if parent_name := child_data['parent']:
  445. eb.parent = armature.edit_bones[parent_name]
  446. eb.length = child_data['length']
  447. eb.matrix = Matrix(
  448. ( child_data['matrix'][:4],
  449. child_data['matrix'][4:8],
  450. child_data['matrix'][8:12],
  451. child_data['matrix'][12:16], )
  452. )
  453. displacement = eb.matrix.to_3x3().transposed().row[1] * child_data['length']
  454. eb.tail = eb.matrix.decompose()[0] + displacement
  455. children.extendleft (child_data['children'].copy())
  456. switch_mode('OBJECT', objects = [armature_object])
  457. # and now we can remove it from the scene collection, since it is in the Armature collection
  458. context.scene.collection.objects.unlink(armature_object)
  459. # note that this will not correct if the object exists and is wrong.
  460. return armature_object
  461. def import_curve_data_to_object(curve_name, curve_data):
  462. # the curve data will come as a single curve's data
  463. from bpy import data
  464. curve_object = data.objects.new(curve_name, data.curves.new(name=curve_name, type='CURVE'))
  465. curve_object.data.dimensions = '3D'
  466. prGreen (curve_name)
  467. for spline_data in curve_data:
  468. spline = curve_object.data.splines.new(type=spline_data['type'])
  469. points_data = spline_data['points']
  470. points_collection = spline.points
  471. if spline.type == 'BEZIER':
  472. # the points are bez_pts
  473. spline.bezier_points.add(len(points_data)-1)
  474. points_collection = spline.bezier_points
  475. else:
  476. spline.points.add(len(points_data)-1) # it starts with 1 already
  477. for i, point_data in enumerate(points_data):
  478. if spline.type == 'BEZIER':
  479. pt = spline.bezier_points[i]
  480. else:
  481. pt = spline.points[i]
  482. for prop in dir(pt):
  483. if prop == 'w':
  484. continue
  485. if prop == 'co' and spline.type != 'BEZIER':
  486. value = point_data[prop]
  487. pt.co = (value[0], value[1], value[2], point_data['w'])
  488. continue
  489. if prop in point_data.keys():
  490. setattr(pt, prop, point_data[prop])
  491. for prop in dir(spline):
  492. if prop in spline_data.keys():
  493. if prop in ['points', 'type', 'index']: continue
  494. setattr(spline, prop, spline_data[prop])
  495. collection = get_default_collection(collection_type="CURVE")
  496. collection.objects.link(curve_object)
  497. return curve_object
  498. def get_component_library_items(path='ADD_ARMATURE'):
  499. from os import path as os_path
  500. from .preferences import get_bl_addon_object
  501. bl_mantis_addon = get_bl_addon_object()
  502. return_value=[]
  503. if bl_mantis_addon:
  504. match path:
  505. case 'ADD_ARMATURE':
  506. components_path = bl_mantis_addon.preferences.ComponentsLibraryFolder
  507. case 'AUTOLOAD':
  508. components_path = bl_mantis_addon.preferences.ComponentsAutoLoadFolder
  509. component_names = {}
  510. from os import walk as os_walk
  511. for path_root, dirs, files, in os_walk(components_path):
  512. for file in files:
  513. relative_file_name = os_path.join(os_path.sep.join(dirs), file)
  514. if file.endswith('.rig'):
  515. component_names[relative_file_name[:-4]] = relative_file_name
  516. if component_names.keys():
  517. for i, (name, path) in enumerate(component_names.items()):
  518. return_value.append( (path, name, path, 'NODE_TREE', i) )
  519. return return_value
  520. ##############################
  521. # READ TREE and also Schema Solve!
  522. ##############################
  523. # TODO: refactor the following two functions, they should be one function with arguments.
  524. def init_connections(nc):
  525. c, hc = [], []
  526. for i in nc.outputs.values():
  527. for l in i.links:
  528. # if l.from_node != nc:
  529. # continue
  530. if l.is_hierarchy:
  531. hc.append(l.to_node)
  532. c.append(l.to_node)
  533. nc.hierarchy_connections = hc
  534. nc.connections = c
  535. def init_dependencies(nc):
  536. c, hc = [], []
  537. for i in nc.inputs.values():
  538. for l in i.links:
  539. # if l.to_node != nc:
  540. # continue
  541. if l.is_hierarchy:
  542. hc.append(l.from_node)
  543. c.append(l.from_node)
  544. nc.hierarchy_dependencies = hc
  545. nc.dependencies = c
  546. def schema_dependency_handle_item(schema, all_nc, item,):
  547. hierarchy = True
  548. from .base_definitions import from_name_filter, to_name_filter
  549. if item.in_out == 'INPUT':
  550. dependencies = schema.dependencies
  551. hierarchy_dependencies = schema.hierarchy_dependencies
  552. if item.parent and item.parent.name == 'Array':
  553. for schema_idname in ['SchemaArrayInput', 'SchemaArrayInputGet', 'SchemaArrayInputAll']:
  554. if (nc := all_nc.get( (*schema.signature, schema_idname) )):
  555. for to_link in nc.outputs[item.name].links:
  556. if to_link.to_socket in to_name_filter:
  557. # hierarchy_reason='a'
  558. hierarchy = False
  559. for from_link in schema.inputs[item.identifier].links:
  560. if from_link.from_socket in from_name_filter:
  561. hierarchy = False
  562. # hierarchy_reason='b'
  563. if from_link.from_node not in dependencies:
  564. if hierarchy:
  565. hierarchy_dependencies.append(from_link.from_node)
  566. dependencies.append(from_link.from_node)
  567. if item.parent and item.parent.name == 'Constant':
  568. if nc := all_nc.get((*schema.signature, 'SchemaConstInput')):
  569. for to_link in nc.outputs[item.name].links:
  570. if to_link.to_socket in to_name_filter:
  571. # hierarchy_reason='dependencies'
  572. hierarchy = False
  573. for from_link in schema.inputs[item.identifier].links:
  574. if from_link.from_socket in from_name_filter:
  575. # hierarchy_reason='d'
  576. hierarchy = False
  577. if from_link.from_node not in dependencies:
  578. if hierarchy:
  579. hierarchy_dependencies.append(from_link.from_node)
  580. dependencies.append(from_link.from_node)
  581. if item.parent and item.parent.name == 'Connection':
  582. if nc := all_nc.get((*schema.signature, 'SchemaIncomingConnection')):
  583. for to_link in nc.outputs[item.name].links:
  584. if to_link.to_socket in to_name_filter:
  585. # hierarchy_reason='e'
  586. hierarchy = False
  587. for from_link in schema.inputs[item.identifier].links:
  588. if from_link.from_socket in from_name_filter:
  589. # hierarchy_reason='f'
  590. hierarchy = False
  591. if from_link.from_node not in dependencies:
  592. if hierarchy:
  593. hierarchy_dependencies.append(from_link.from_node)
  594. dependencies.append(from_link.from_node)
  595. def init_schema_dependencies(schema, all_nc):
  596. """ Initialize the dependencies for Schema, and mark them as hierarchy or non-hierarchy dependencies
  597. Non-hierarchy dependencies are e.g. drivers and custom transforms.
  598. """
  599. tree = schema.prototype.node_tree
  600. if tree is None:
  601. raise RuntimeError(f"Cannot get dependencies for schema {schema}")
  602. schema.dependencies = []
  603. schema.hierarchy_dependencies = []
  604. for l in schema.inputs["Schema Length"].links:
  605. schema.hierarchy_dependencies.append(l.from_node)
  606. if tree.interface:
  607. for item in tree.interface.items_tree:
  608. if item.item_type == 'PANEL':
  609. continue
  610. schema_dependency_handle_item(schema, all_nc, item,)
  611. def check_and_add_root(n, roots, include_non_hierarchy=False):
  612. if (include_non_hierarchy * len(n.dependencies)) > 0:
  613. return
  614. elif len(n.hierarchy_dependencies) > 0:
  615. return
  616. roots.append(n)
  617. def get_link_in_out(link):
  618. from .base_definitions import replace_types
  619. from_name, to_name = link.from_socket.node.name, link.to_socket.node.name
  620. # catch special bl_idnames and bunch the connections up
  621. if link.from_socket.node.bl_idname in replace_types:
  622. from_name = link.from_socket.node.bl_idname
  623. if link.to_socket.node.bl_idname in replace_types:
  624. to_name = link.to_socket.node.bl_idname
  625. return from_name, to_name
  626. def link_node_containers(tree_path_names, link, local_nc, from_suffix='', to_suffix=''):
  627. dummy_types = ["DUMMY", "DUMMY_SCHEMA"]
  628. from_name, to_name = get_link_in_out(link)
  629. nc_from = local_nc.get( (*tree_path_names, from_name+from_suffix) )
  630. nc_to = local_nc.get( (*tree_path_names, to_name+to_suffix))
  631. if (nc_from and nc_to):
  632. from_s, to_s = link.from_socket.name, link.to_socket.name
  633. if nc_to.node_type in dummy_types: to_s = link.to_socket.identifier
  634. if nc_from.node_type in dummy_types: from_s = link.from_socket.identifier
  635. try:
  636. connection = nc_from.outputs[from_s].connect(node=nc_to, socket=to_s, sort_id=link.multi_input_sort_id)
  637. if connection is None:
  638. prWhite(f"Already connected: {from_name}:{from_s}->{to_name}:{to_s}")
  639. return connection
  640. except KeyError as e:
  641. prRed(f"{nc_from}:{from_s} or {nc_to}:{to_s} missing; review the connections printed below:")
  642. print (nc_from.outputs.keys())
  643. print (nc_to.inputs.keys())
  644. raise e
  645. else:
  646. prRed(nc_from, nc_to, (*tree_path_names, from_name+from_suffix), (*tree_path_names, to_name+to_suffix))
  647. raise RuntimeError(wrapRed("Link not connected: %s -> %s in tree %s" % (from_name, to_name, tree_path_names[-1])))
  648. def get_all_dependencies(nc):
  649. from .base_definitions import GraphError
  650. """ find all dependencies for a mantis node"""
  651. nodes = []
  652. check_nodes = [nc]
  653. nodes_checked = set()
  654. while (len(check_nodes) > 0):
  655. node = check_nodes.pop()
  656. nodes_checked.add (node)
  657. connected_nodes = node.hierarchy_dependencies
  658. for new_node in connected_nodes:
  659. if new_node in nodes:
  660. continue
  661. nodes.append(new_node)
  662. if new_node not in nodes_checked:
  663. check_nodes.append(new_node)
  664. return nodes
  665. def get_all_nodes_of_type(base_tree, bl_idname):
  666. nodes = []
  667. check_nodes = list(base_tree.nodes)
  668. while (len(check_nodes) > 0):
  669. node = check_nodes.pop()
  670. if node.bl_idname in bl_idname:
  671. nodes.append(node)
  672. if hasattr(node, "node_tree"):
  673. check_nodes.extend(list(node.node_tree.nodes))
  674. return nodes
  675. def trace_all_nodes_from_root(root, nodes):
  676. from .base_definitions import GraphError
  677. """ find all dependencies for a mantis node"""
  678. nodes.add(root); check_nodes = [root]
  679. nodes_checked = set()
  680. while (len(check_nodes) > 0):
  681. node = check_nodes.pop(); nodes_checked.add (node)
  682. connected_nodes = []
  683. for output in node.outputs:
  684. for l in output.links:
  685. if l.to_node not in nodes:
  686. connected_nodes.append(l.to_node)
  687. for new_node in connected_nodes:
  688. nodes.add(new_node)
  689. if new_node not in nodes_checked:
  690. check_nodes.append(new_node)
  691. return nodes
  692. ##################################################################################################
  693. # misc
  694. ##################################################################################################
  695. # TODO: get the matrix to return a mathutils.Matrix so I don't need a function call here
  696. def to_mathutils_value(socket):
  697. if hasattr(socket, "default_value"):
  698. val = socket.default_value
  699. if socket.bl_idname in ['MatrixSocket']:
  700. return socket.TellValue()
  701. else:
  702. return val
  703. else:
  704. return None
  705. def all_trees_in_tree(base_tree, selected=False):
  706. """ Recursively finds all trees referenced in a given base-tree."""
  707. # note that this is recursive but not by tail-end recursion
  708. # a while-loop is a better way to do recursion in Python.
  709. trees = [base_tree]
  710. can_descend = True
  711. check_trees = [base_tree]
  712. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  713. new_trees = []
  714. while (len(check_trees) > 0):
  715. tree = check_trees.pop()
  716. for node in tree.nodes:
  717. if selected == True and node.select == False:
  718. continue
  719. if new_tree := getattr(node, "node_tree", None):
  720. if new_tree in trees: continue
  721. new_trees.append(new_tree)
  722. trees.append(new_tree)
  723. check_trees = new_trees
  724. return trees
  725. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  726. def SugiyamaGraph(tree, iterations):
  727. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  728. class defaultview(object):
  729. w,h = 1,1
  730. xz = (0,0)
  731. graph = Graph()
  732. no_links = set()
  733. verts = {}
  734. for n in tree.nodes:
  735. if n.select == True:
  736. v = Vertex(n.name)
  737. v.view = defaultview()
  738. v.view.xy = n.location
  739. v.view.h = n.height*2.5
  740. v.view.w = n.width*2.2
  741. verts[n.name] = v
  742. no_links.add(n.name)
  743. graph.add_vertex(v)
  744. n.select=False
  745. edges = []
  746. inverted_edges=[]
  747. not_a_root = set()
  748. for link in tree.links:
  749. if (link.from_node.name not in verts.keys()) or (link.to_node.name not in verts.keys()):
  750. continue # problem??
  751. weight = 1 # maybe this is useful
  752. not_a_root.add(link.to_node.name) # if it has a edge-input it is not a root.
  753. e = Edge(verts[link.from_node.name], verts[link.to_node.name], weight)
  754. graph.add_edge(e)
  755. edges.append(e )
  756. if link.is_valid == False:
  757. inverted_edges.append(e)
  758. if link.from_node.name in no_links:
  759. no_links.remove(link.from_node.name)
  760. if link.to_node.name in no_links:
  761. no_links.remove(link.to_node.name)
  762. try:
  763. from grandalf.layouts import SugiyamaLayout
  764. # .C[0] is the first "graph core" that contains a connected graph.
  765. sug = SugiyamaLayout(graph.C[0])
  766. sug.init_all()
  767. sug.draw(iterations)
  768. # Digco is good for small graphs.
  769. # from grandalf.layouts import DigcoLayout
  770. # dco = DigcoLayout(graph.C[0])
  771. # dco.init_all()
  772. # dco.draw(iterations)
  773. except KeyboardInterrupt:
  774. pass # just use what it has calculated so far, I guess
  775. for v in graph.C[0].sV:
  776. for n in tree.nodes:
  777. if n.name == v.data:
  778. n.location.x = v.view.xy[1]
  779. n.location.y = v.view.xy[0]
  780. n.select = True
  781. # now we can take all the input nodes and try to put them in a sensible place
  782. # not sure why but this absolutely does not do anything
  783. for n_name in no_links:
  784. n = tree.nodes.get(n_name)
  785. next_node = None
  786. for output in n.outputs:
  787. if output.is_linked == True:
  788. next_node = output.links[0].to_node
  789. break
  790. # let's see if the next node
  791. if next_node:
  792. # need to find the other node in the same layer...
  793. other_node = None
  794. for s_input in next_node.inputs:
  795. if s_input.is_linked:
  796. other_node = s_input.links[0].from_node
  797. if other_node is n:
  798. continue
  799. else:
  800. break
  801. if other_node:
  802. n.location = other_node.location
  803. n.location.y -= other_node.height*2
  804. else: # we'll just position it next to the next node
  805. n.location = next_node.location
  806. n.location.x -= next_node.width*1.5
  807. def project_point_to_plane(point, origin, normal):
  808. return point - normal.dot(point- origin)*normal
  809. ##################################################################################################
  810. # stuff I should probably refactor!!
  811. ##################################################################################################
  812. # This is really, really stupid way to do this
  813. def gen_nc_input_for_data(socket):
  814. # Class List #TODO deduplicate
  815. from . import xForm_nodes, link_nodes, misc_nodes, primitives_nodes, deformer_nodes, math_nodes, schema_nodes
  816. from .internal_containers import NoOpNode
  817. classes = {}
  818. for module in [xForm_nodes, link_nodes, misc_nodes, primitives_nodes, deformer_nodes, math_nodes, schema_nodes]:
  819. for cls in module.TellClasses():
  820. classes[cls.__name__] = cls
  821. #
  822. socket_class_map = {
  823. "MatrixSocket" : classes["InputMatrix"],
  824. "xFormSocket" : None,
  825. "RelationshipSocket" : NoOpNode,
  826. "DeformerSocket" : NoOpNode,
  827. "GeometrySocket" : classes["InputExistingGeometryData"],
  828. "EnableSocket" : classes["InputBoolean"],
  829. "HideSocket" : classes["InputBoolean"],
  830. #
  831. "DriverSocket" : None,
  832. "DriverVariableSocket" : None,
  833. "FCurveSocket" : None,
  834. "KeyframeSocket" : None,
  835. "BoneCollectionSocket" : classes["InputString"],
  836. #
  837. "xFormParameterSocket" : None,
  838. "ParameterBoolSocket" : classes["InputBoolean"],
  839. "ParameterIntSocket" : classes["InputFloat"], #TODO: make an Int node for this
  840. "ParameterFloatSocket" : classes["InputFloat"],
  841. "ParameterVectorSocket" : classes["InputVector"],
  842. "ParameterStringSocket" : classes["InputString"],
  843. #
  844. "TransformSpaceSocket" : classes["InputTransformSpace"],
  845. "BooleanSocket" : classes["InputBoolean"],
  846. "BooleanThreeTupleSocket" : classes["InputBooleanThreeTuple"],
  847. "RotationOrderSocket" : classes["InputRotationOrder"],
  848. "QuaternionSocket" : None,
  849. "QuaternionSocketAA" : None,
  850. "UnsignedIntSocket" : classes["InputFloat"],
  851. "IntSocket" : classes["InputFloat"],
  852. "StringSocket" : classes["InputString"],
  853. #
  854. "BoolUpdateParentNode" : classes["InputBoolean"],
  855. "IKChainLengthSocket" : classes["InputFloat"],
  856. "EnumInheritScale" : classes["InputString"],
  857. "EnumRotationMix" : classes["InputString"],
  858. "EnumRotationMixCopyTransforms" : classes["InputString"],
  859. "EnumMaintainVolumeStretchTo" : classes["InputString"],
  860. "EnumRotationStretchTo" : classes["InputString"],
  861. "EnumTrackAxis" : classes["InputString"],
  862. "EnumUpAxis" : classes["InputString"],
  863. "EnumLockAxis" : classes["InputString"],
  864. "EnumLimitMode" : classes["InputString"],
  865. "EnumYScaleMode" : classes["InputString"],
  866. "EnumXZScaleMode" : classes["InputString"],
  867. "EnumCurveSocket" : classes["InputString"],
  868. "EnumMetaRigSocket" : classes["InputString"],
  869. # Deformers
  870. "EnumSkinning" : classes["InputString"],
  871. #
  872. "FloatSocket" : classes["InputFloat"],
  873. "FloatFactorSocket" : classes["InputFloat"],
  874. "FloatPositiveSocket" : classes["InputFloat"],
  875. "FloatAngleSocket" : classes["InputFloat"],
  876. "VectorSocket" : classes["InputVector"],
  877. "VectorEulerSocket" : classes["InputVector"],
  878. "VectorTranslationSocket" : classes["InputVector"],
  879. "VectorScaleSocket" : classes["InputVector"],
  880. # Drivers
  881. "EnumDriverVariableType" : classes["InputString"],
  882. "EnumDriverVariableEvaluationSpace" : classes["InputString"],
  883. "EnumDriverRotationMode" : classes["InputString"],
  884. "EnumDriverType" : classes["InputString"],
  885. "EnumKeyframeInterpTypeSocket" : classes["InputString"],
  886. "EnumKeyframeBezierHandleTypeSocket" : classes["InputString"],
  887. # Math
  888. "MathFloatOperation" : classes["InputString"],
  889. "MathVectorOperation" : classes["InputString"],
  890. "MatrixTransformOperation" : classes["InputString"],
  891. # Schema
  892. "WildcardSocket" : None,
  893. }
  894. return socket_class_map.get(socket.bl_idname, None)
  895. ####################################
  896. # CURVE STUFF
  897. ####################################
  898. def make_perpendicular(v1, v2):
  899. from .base_definitions import FLOAT_EPSILON
  900. if (v1.length_squared < FLOAT_EPSILON) or (v2.length_squared < FLOAT_EPSILON):
  901. raise RuntimeError("Cannot generate perpendicular vetor for zero-length vector")
  902. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  903. perpendicular = v2 - projected
  904. return perpendicular
  905. # this stuff could be branchless but I don't use it much TODO
  906. def cap(val, maxValue):
  907. if (val > maxValue):
  908. return maxValue
  909. return val
  910. def capMin(val, minValue):
  911. if (val < minValue):
  912. return minValue
  913. return val
  914. def wrap(min : float, max : float, value: float) -> float:
  915. range = max-min; remainder = value % range
  916. if remainder > max: return min + remainder-max
  917. else: return remainder
  918. def lerpVal(a, b, fac = 0.5):
  919. return a + ( (b-a) * fac)
  920. #wtf this doesn't do anything even remotely similar to wrap
  921. # HACK BAD FIXME UNBREAK ME BAD
  922. # I don't understand what this function does but I am using it in multiple places?
  923. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  924. if (val > maxValue):
  925. return (-1 * ((maxValue - val) + 1))
  926. if ((minValue) and (val < minValue)):
  927. return (val + maxValue)
  928. return val
  929. #TODO clean this up
  930. def extract_spline_suffix(spline_index):
  931. return ".spline."+str(spline_index).zfill(3)+".extracted"
  932. def do_extract_spline(data, spline):
  933. remove_me = []
  934. for other_spline in data.splines:
  935. if other_spline != spline: remove_me.append(other_spline)
  936. while remove_me: data.splines.remove(remove_me.pop())
  937. def extract_spline(curve, spline_index):
  938. """ Given a curve object and spline index, returns a new object
  939. containing only the selcted spline. The new object is bound to
  940. the original curve.
  941. """
  942. if len(curve.data.splines) == 1:
  943. return curve # nothing to do here.
  944. spline_suffix = extract_spline_suffix(spline_index)
  945. from bpy import data
  946. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  947. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  948. # if the data exists, it is probably stale, so delete it and start over.
  949. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  950. data.curves.remove(old_data)
  951. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  952. new_ob.data = new_data
  953. # do not check for index error here, it is the calling function's responsibility
  954. do_extract_spline(new_data, new_data.splines[spline_index])
  955. return new_ob
  956. def bind_extracted_spline_to_curve(new_ob, curve):
  957. # Set up a relationship between the new object and the old object
  958. # now, weirdly enough - we can't use parenting very easily because Blender
  959. # defines the parent on a curve relative to the evaluated path animation
  960. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  961. from .xForm_nodes import reset_object_data
  962. reset_object_data(new_ob)
  963. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  964. new_ob.parent=curve
  965. return new_ob
  966. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  967. # we're storing it separately like this to ensure all nodes use the same
  968. # object if they extract the same spline for use by Mantis.
  969. # this should be transparent to the user since it is working around a
  970. # a limitation in Blender.
  971. extracted_spline_name = proto_curve.name+extract_spline_suffix(spline_index)
  972. if curve := mContext.b_objects.get(extracted_spline_name):
  973. return curve
  974. else:
  975. curve = extract_spline(proto_curve, spline_index)
  976. if curve.name != proto_curve.name: # if there is only one spline, no
  977. bind_extracted_spline_to_curve(curve, proto_curve)# dupe is created.
  978. mContext.b_objects[extracted_spline_name] = curve
  979. return curve
  980. def nurbs_copy_bez_spline(curve, bez_spline, do_setup=True):
  981. other_spline= curve.data.splines.new('NURBS')
  982. other_spline.use_endpoint_u=True
  983. other_spline.use_bezier_u=True
  984. bez_pts = bez_spline.bezier_points
  985. bez_data=[]
  986. for i, bez_pt in enumerate(bez_pts):
  987. if i > 0:
  988. bez_data.append(bez_pt.handle_left.copy())
  989. bez_data.append(bez_pt.co.copy())
  990. if i != len(bez_pts)-1:
  991. bez_data.append(bez_pt.handle_right.copy())
  992. other_spline.points.add(len(bez_data)-1)
  993. for i, pt in enumerate(bez_data):
  994. other_spline.points[i].co=(*pt,1.0) # add the W value here
  995. if do_setup: # do the stuff that makes it behave the same as a bez spline
  996. other_spline.use_endpoint_u = True; other_spline.use_bezier_u = True
  997. other_spline.order_u=4 # set to 1 for poly
  998. return other_spline
  999. def RibbonMeshEdgeLengths(m, ribbon):
  1000. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  1001. lengths = []
  1002. for i in range( len( tE ) ): #tE and bE are same length
  1003. if (c == True):
  1004. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  1005. else:
  1006. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  1007. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  1008. if (c == True):
  1009. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  1010. else:
  1011. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  1012. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  1013. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  1014. # get the center, edges may not be straight so total length
  1015. # of one edge may be more than the ribbon center's length
  1016. lengths.append(( v - vNext ).length)
  1017. return lengths
  1018. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  1019. from .base_definitions import FLOAT_EPSILON
  1020. crvRadius = 0
  1021. crv.data.offset = 0
  1022. if (crv.data.bevel_depth < FLOAT_EPSILON):
  1023. crvRadius = crv.data.extrude
  1024. else: #Set ribbon from bevel depth
  1025. crvRadius = crv.data.bevel_depth
  1026. crv.data.bevel_depth = 0
  1027. crv.data.extrude = crvRadius
  1028. if (crvRadius < FLOAT_EPSILON):
  1029. crv.data.extrude = defaultRadius
  1030. def SetRibbonData(m, ribbon):
  1031. #maybe this could be incorporated into the DetectWireEdges function?
  1032. #maybe I can check for closed poly curves here? under what other circumstance
  1033. # will I find the ends of the wire have identical coordinates?
  1034. ribbonData = []
  1035. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  1036. #
  1037. lengths = RibbonMeshEdgeLengths(m, ribbon)
  1038. lengths.append(0)
  1039. totalLength = sum(lengths)
  1040. # m.calc_normals() #calculate normals
  1041. # it appears this has been removed.
  1042. for i, (t, b) in enumerate(zip(tE, bE)):
  1043. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  1044. tNext = tE[ind]; bNext = bE[ind]
  1045. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  1046. #if this is a circle, the last v in vertData has a length, otherwise 0
  1047. return ribbonData, totalLength
  1048. def WireMeshEdgeLengths(m, wire):
  1049. circle = False
  1050. vIndex = wire.copy()
  1051. for e in m.edges:
  1052. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  1053. #this checks for an edge between the first and last vertex in the wire
  1054. circle = True
  1055. break
  1056. lengths = []
  1057. for i in range(len(vIndex)):
  1058. v = m.vertices[vIndex[i]]
  1059. if (circle == True):
  1060. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  1061. else:
  1062. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  1063. vNext = m.vertices[vNextInd]
  1064. lengths.append(( v.co - vNext.co ).length)
  1065. #if this is a circular wire mesh, this should wrap instead of cap
  1066. return lengths
  1067. def GetDataFromWire(m, wire):
  1068. vertData = []
  1069. vIndex = wire.copy()
  1070. lengths = WireMeshEdgeLengths(m, wire)
  1071. lengths.append(0)
  1072. totalLength = sum(lengths)
  1073. for i, vInd in enumerate(vIndex):
  1074. #-1 to avoid IndexError
  1075. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  1076. vertData.append((vInd, vNext, lengths[i]))
  1077. #if this is a circle, the last v in vertData has a length, otherwise 0
  1078. return vertData, totalLength
  1079. def DetectWireEdges(mesh):
  1080. # Returns a list of vertex indices belonging to wire meshes
  1081. # NOTE: this assumes a mesh object with only wire meshes
  1082. ret = []
  1083. import bmesh
  1084. bm = bmesh.new()
  1085. try:
  1086. bm.from_mesh(mesh)
  1087. ends = []
  1088. for v in bm.verts:
  1089. if (len(v.link_edges) == 1):
  1090. ends.append(v.index)
  1091. for e in bm.edges:
  1092. assert (e.is_wire == True),"This function can only run on wire meshes"
  1093. if (e.verts[1].index - e.verts[0].index != 1):
  1094. ends.append(e.verts[1].index)
  1095. ends.append(e.verts[0].index)
  1096. for i in range(len(ends)//2): # // is floor division
  1097. beg = ends[i*2]
  1098. end = ends[(i*2)+1]
  1099. indices = [(j + beg) for j in range ((end - beg) + 1)]
  1100. ret.append(indices)
  1101. finally:
  1102. bm.free()
  1103. return ret
  1104. def FindNearestPointOnWireMesh(m, pointsList):
  1105. from mathutils import Vector
  1106. from mathutils.geometry import intersect_point_line
  1107. from math import sqrt
  1108. wires = DetectWireEdges(m)
  1109. ret = []
  1110. # prevFactor = None
  1111. for wire, points in zip(wires, pointsList):
  1112. vertData, total_length = GetDataFromWire(m, wire)
  1113. factorsOut = []
  1114. for p in points:
  1115. prevDist = float('inf')
  1116. curDist = float('inf')
  1117. v1 = None
  1118. v2 = None
  1119. for i in range(len(vertData) - 1):
  1120. #but it shouldn't check the last one
  1121. if (p == m.vertices[i].co):
  1122. v1 = vertData[i]
  1123. v2 = vertData[i+1]
  1124. offset = 0
  1125. break
  1126. else:
  1127. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  1128. ((m.vertices[vertData[i][1]].co - p).length) )/2
  1129. if (curDist < prevDist):
  1130. v1 = vertData[i]
  1131. v2 = vertData[i+1]
  1132. prevDist = curDist
  1133. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  1134. m.vertices[v2[0]].co)[1]
  1135. if (offset < 0):
  1136. offset = 0
  1137. elif (offset > 1):
  1138. offset = 1
  1139. # Assume the vertices are in order
  1140. v1Length = 0
  1141. v2Length = v2[2]
  1142. for i in range(v1[0]):
  1143. v1Length += vertData[i][2]
  1144. factor = ((offset * (v2Length)) + v1Length )/total_length
  1145. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  1146. factorsOut.append(factor)
  1147. ret.append( factorsOut )
  1148. return ret
  1149. def mesh_from_curve(crv, context, ribbon=True):
  1150. """Utility function for converting a mesh to a curve
  1151. which will return the correct mesh even with modifiers"""
  1152. import bpy
  1153. m = None
  1154. bevel = crv.data.bevel_depth
  1155. extrude = crv.data.extrude
  1156. offset = crv.data.offset
  1157. try:
  1158. if (len(crv.modifiers) > 0):
  1159. do_unlink = False
  1160. if (not context.scene.collection.all_objects.get(crv.name)):
  1161. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  1162. do_unlink = True
  1163. dg = context.view_layer.depsgraph
  1164. # just gonna modify it for now lol
  1165. if ribbon:
  1166. EnsureCurveIsRibbon(crv)
  1167. else:
  1168. crv.data.bevel_depth=0
  1169. crv.data.extrude=0
  1170. crv.data.offset=0
  1171. # try:
  1172. dg.update()
  1173. mOb = crv.evaluated_get(dg)
  1174. m = bpy.data.meshes.new_from_object(mOb)
  1175. m.name=crv.data.name+'_mesh'
  1176. if (do_unlink):
  1177. context.collection.objects.unlink(crv)
  1178. else: # (ಥ﹏ಥ) why can't I just use this !
  1179. # for now I will just do it like this
  1180. if ribbon:
  1181. EnsureCurveIsRibbon(crv)
  1182. else:
  1183. crv.data.bevel_depth=0
  1184. crv.data.extrude=0
  1185. crv.data.offset=0
  1186. m = bpy.data.meshes.new_from_object(crv)
  1187. finally:
  1188. crv.data.bevel_depth = bevel
  1189. crv.data.extrude = extrude
  1190. crv.data.offset = offset
  1191. return m
  1192. def DetectRibbon(f, bm, skipMe):
  1193. fFirst = f.index
  1194. cont = True
  1195. circle = False
  1196. tEdge, bEdge = [],[]
  1197. while (cont == True):
  1198. skipMe.add(f.index)
  1199. tEdge.append (f.loops[0].vert.index) # top-left
  1200. bEdge.append (f.loops[3].vert.index) # bottom-left
  1201. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  1202. nFaces = nEdge.link_faces
  1203. if (len(nFaces) == 1):
  1204. cont = False
  1205. else:
  1206. for nFace in nFaces:
  1207. if (nFace != f):
  1208. f = nFace
  1209. break
  1210. if (f.index == fFirst):
  1211. cont = False
  1212. circle = True
  1213. if (cont == False): # we've reached the end, get the last two:
  1214. tEdge.append (f.loops[1].vert.index) # top-right
  1215. bEdge.append (f.loops[2].vert.index) # bottom-right
  1216. # this will create a loop for rings --
  1217. # "the first shall be the last and the last shall be first"
  1218. return (tEdge,bEdge,circle)
  1219. def DetectRibbons(m, fReport = None):
  1220. # Returns list of vertex indices belonging to ribbon mesh edges
  1221. # NOTE: this assumes a mesh object with only ribbon meshes
  1222. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  1223. import bmesh
  1224. bm = bmesh.new()
  1225. bm.from_mesh(m)
  1226. mIslands, mIsland = [], []
  1227. skipMe = set()
  1228. bm.faces.ensure_lookup_table()
  1229. #first, get a list of mesh islands
  1230. for f in bm.faces:
  1231. if (f.index in skipMe):
  1232. continue #already done here
  1233. checkMe = [f]
  1234. while (len(checkMe) > 0):
  1235. facesFound = 0
  1236. for f in checkMe:
  1237. if (f.index in skipMe):
  1238. continue #already done here
  1239. mIsland.append(f)
  1240. skipMe.add(f.index)
  1241. for e in f.edges:
  1242. checkMe += e.link_faces
  1243. if (facesFound == 0):
  1244. #this is the last iteration
  1245. mIslands.append(mIsland)
  1246. checkMe, mIsland = [], []
  1247. ribbons = []
  1248. skipMe = set() # to store ends already checked
  1249. for mIsl in mIslands:
  1250. ribbon = None
  1251. first = float('inf')
  1252. for f in mIsl:
  1253. if (f.index in skipMe):
  1254. continue #already done here
  1255. if (f.index < first):
  1256. first = f.index
  1257. adjF = 0
  1258. for e in f.edges:
  1259. adjF+= (len(e.link_faces) - 1)
  1260. # every face other than this one is added to the list
  1261. if (adjF == 1):
  1262. ribbon = (DetectRibbon(f, bm, skipMe) )
  1263. break
  1264. if (ribbon == None):
  1265. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  1266. ribbons.append(ribbon)
  1267. # print (ribbons)
  1268. return ribbons
  1269. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  1270. #Note, factors list should be equal in length the the number of wires
  1271. #Now working for multiple wires, ugly tho
  1272. if (ribbons == None):
  1273. ribbons = DetectRibbons(m, fReport=fReport)
  1274. if (ribbons is None):
  1275. if (fReport):
  1276. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  1277. else:
  1278. print ("No ribbon to get data from.")
  1279. return None
  1280. ret = []
  1281. for factors, ribbon in zip(factorsList, ribbons):
  1282. points = []
  1283. widths = []
  1284. normals = []
  1285. ribbonData, totalLength = SetRibbonData(m, ribbon)
  1286. for fac in factors:
  1287. if (fac == 0):
  1288. data = ribbonData[0]
  1289. curFac = 0
  1290. elif (fac == 1):
  1291. data = ribbonData[-1]
  1292. curFac = 0
  1293. else:
  1294. targetLength = totalLength * fac
  1295. data = ribbonData[0]
  1296. curLength = 0
  1297. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  1298. if (curLength >= targetLength):
  1299. break
  1300. curLength += length
  1301. data = ( (t, b), (tNext, bNext), length,)
  1302. targetLengthAtEdge = (curLength - targetLength)
  1303. if (targetLength == 0):
  1304. curFac = 0
  1305. elif (targetLength == totalLength):
  1306. curFac = 1
  1307. else:
  1308. # NOTE: This can be Zero. Find out why!
  1309. if data[2] == 0:
  1310. curFac=0
  1311. else:
  1312. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  1313. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  1314. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  1315. #location
  1316. loc1 = (t1.co).lerp(b1.co, 0.5)
  1317. loc2 = (t2.co).lerp(b2.co, 0.5)
  1318. #width
  1319. w1 = (t1.co - b1.co).length/2
  1320. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  1321. #normal
  1322. n1 = (t1.normal).slerp(b1.normal, 0.5)
  1323. n2 = (t1.normal).slerp(b2.normal, 0.5)
  1324. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  1325. curFac = 0
  1326. #don't interpolate if at the end of a ribbon that isn't circular
  1327. if ( 0 < curFac < 1):
  1328. outPoint = loc1.lerp(loc2, curFac)
  1329. outNorm = n1.lerp(n2, curFac)
  1330. outWidth = w1 + ( (w2-w1) * curFac)
  1331. elif (curFac <= 0):
  1332. outPoint = loc1.copy()
  1333. outNorm = n1
  1334. outWidth = w1
  1335. elif (curFac >= 1):
  1336. outPoint = loc2.copy()
  1337. outNorm = n2
  1338. outWidth = w2
  1339. outPoint = mat @ outPoint
  1340. outNorm.normalize()
  1341. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1342. widths.append ( outWidth )
  1343. normals.append( outNorm )
  1344. ret.append( (points, widths, normals) )
  1345. return ret # this is a list of tuples containing three lists
  1346. #This bisection search is generic, and it searches based on the
  1347. # magnitude of the error, rather than the sign.
  1348. # If the sign of the error is meaningful, a simpler function
  1349. # can be used.
  1350. def do_bisect_search_by_magnitude(
  1351. owner,
  1352. attribute,
  1353. index = None,
  1354. test_function = None,
  1355. modify = None,
  1356. max_iterations = 10000,
  1357. threshold = 0.0001,
  1358. thresh2 = 0.0005,
  1359. context = None,
  1360. update_dg = None,
  1361. ):
  1362. from math import floor
  1363. i = 0; best_so_far = 0; best = float('inf')
  1364. min = 0; center = max_iterations//2; max = max_iterations
  1365. # enforce getting the absolute value, in case the function has sign information
  1366. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1367. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1368. while (i <= max_iterations):
  1369. upper = (max - ((max-center))//2)
  1370. modify(owner, attribute, index, upper, context = context); error1 = test()
  1371. lower = (center - ((center-min))//2)
  1372. modify(owner, attribute, index, lower, context = context); error2 = test()
  1373. if (error1 < error2):
  1374. min = center
  1375. center, check = upper, upper
  1376. error = error1
  1377. else:
  1378. max = center
  1379. center, check = lower, lower
  1380. error = error2
  1381. if (error <= threshold) or (min == max-1):
  1382. break
  1383. if (error < thresh2):
  1384. j = min
  1385. while (j < max):
  1386. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1387. error = test()
  1388. if (error < best):
  1389. best_so_far = j; best = error
  1390. if (error <= threshold):
  1391. break
  1392. j+=1
  1393. else: # loop has completed without finding a solution
  1394. i = best_so_far; error = test()
  1395. modify(owner, attribute, index, best_so_far, context = context)
  1396. break
  1397. if (error < best):
  1398. best_so_far = check; best = error
  1399. i+=1
  1400. if update_dg:
  1401. update_dg.update()
  1402. else: # Loop has completed without finding a solution
  1403. i = best_so_far
  1404. modify(owner, attribute, best_so_far, context = context); i+=1