utilities.py 65 KB

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