utilities.py 58 KB

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