utilities.py 68 KB

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