utilities.py 68 KB

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