utilities.py 65 KB

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