utilities.py 50 KB

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