utilities.py 53 KB

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