utilities.py 57 KB

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