utilities.py 58 KB

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