utilities.py 65 KB

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