utilities.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  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. ##################################################################################################
  377. # misc
  378. ##################################################################################################
  379. # TODO: get the matrix to return a mathutils.Matrix so I don't need a function call here
  380. def to_mathutils_value(socket):
  381. if hasattr(socket, "default_value"):
  382. val = socket.default_value
  383. if socket.bl_idname in ['MatrixSocket']:
  384. return socket.TellValue()
  385. else:
  386. return val
  387. else:
  388. return None
  389. def all_trees_in_tree(base_tree, selected=False):
  390. """ Recursively finds all trees referenced in a given base-tree."""
  391. # note that this is recursive but not by tail-end recursion
  392. # a while-loop is a better way to do recursion in Python.
  393. trees = [base_tree]
  394. can_descend = True
  395. check_trees = [base_tree]
  396. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  397. new_trees = []
  398. while (len(check_trees) > 0):
  399. tree = check_trees.pop()
  400. for node in tree.nodes:
  401. if selected == True and node.select == False:
  402. continue
  403. if new_tree := getattr(node, "node_tree", None):
  404. if new_tree in trees: continue
  405. new_trees.append(new_tree)
  406. trees.append(new_tree)
  407. check_trees = new_trees
  408. return trees
  409. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  410. def SugiyamaGraph(tree, iterations):
  411. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  412. class defaultview(object):
  413. w,h = 1,1
  414. xz = (0,0)
  415. no_links = set()
  416. verts = {}
  417. for n in tree.nodes:
  418. has_links=False
  419. for inp in n.inputs:
  420. if inp.is_linked:
  421. has_links=True
  422. break
  423. else:
  424. no_links.add(n.name)
  425. for out in n.outputs:
  426. if out.is_linked:
  427. has_links=True
  428. break
  429. else:
  430. try:
  431. no_links.remove(n.name)
  432. except KeyError:
  433. pass
  434. if not has_links:
  435. continue
  436. v = Vertex(n.name)
  437. v.view = defaultview()
  438. v.view.xy = n.location
  439. v.view.h = n.height*2.5
  440. v.view.w = n.width*2.2
  441. verts[n.name] = v
  442. edges = []
  443. for link in tree.links:
  444. weight = 1 # maybe this is useful
  445. edges.append(Edge(verts[link.from_node.name], verts[link.to_node.name], weight) )
  446. graph = Graph(verts.values(), edges)
  447. from grandalf.layouts import SugiyamaLayout
  448. sug = SugiyamaLayout(graph.C[0]) # no idea what .C[0] is
  449. roots=[]
  450. for node in tree.nodes:
  451. has_links=False
  452. for inp in node.inputs:
  453. if inp.is_linked:
  454. has_links=True
  455. break
  456. for out in node.outputs:
  457. if out.is_linked:
  458. has_links=True
  459. break
  460. if not has_links:
  461. continue
  462. if len(node.inputs)==0:
  463. roots.append(verts[node.name])
  464. else:
  465. for inp in node.inputs:
  466. if inp.is_linked==True:
  467. break
  468. else:
  469. roots.append(verts[node.name])
  470. sug.init_all(roots=roots,)
  471. sug.draw(iterations)
  472. for v in graph.C[0].sV:
  473. for n in tree.nodes:
  474. if n.name == v.data:
  475. n.location.x = v.view.xy[1]
  476. n.location.y = v.view.xy[0]
  477. # now we can take all the input nodes and try to put them in a sensible place
  478. for n_name in no_links:
  479. n = tree.nodes.get(n_name)
  480. next_n = None
  481. next_node = None
  482. for output in n.outputs:
  483. if output.is_linked == True:
  484. next_node = output.links[0].to_node
  485. break
  486. # let's see if the next node
  487. if next_node:
  488. # need to find the other node in the same layer...
  489. other_node = None
  490. for s_input in next_node.inputs:
  491. if s_input.is_linked:
  492. other_node = s_input.links[0].from_node
  493. if other_node is n:
  494. continue
  495. else:
  496. break
  497. if other_node:
  498. n.location = other_node.location
  499. n.location.y -= other_node.height*2
  500. else: # we'll just position it next to the next node
  501. n.location = next_node.location
  502. n.location.x -= next_node.width*1.5
  503. def project_point_to_plane(point, origin, normal):
  504. return point - normal.dot(point- origin)*normal
  505. ##################################################################################################
  506. # stuff I should probably refactor!!
  507. ##################################################################################################
  508. # This is really, really stupid way to do this
  509. def gen_nc_input_for_data(socket):
  510. # Class List #TODO deduplicate
  511. from . import xForm_containers, link_containers, misc_nodes, primitives_containers, deformer_containers, math_containers, schema_containers
  512. from .internal_containers import NoOpNode
  513. classes = {}
  514. for module in [xForm_containers, link_containers, misc_nodes, primitives_containers, deformer_containers, math_containers, schema_containers]:
  515. for cls in module.TellClasses():
  516. classes[cls.__name__] = cls
  517. #
  518. socket_class_map = {
  519. "MatrixSocket" : classes["InputMatrix"],
  520. "xFormSocket" : None,
  521. "RelationshipSocket" : NoOpNode,
  522. "DeformerSocket" : NoOpNode,
  523. "GeometrySocket" : classes["InputExistingGeometryData"],
  524. "EnableSocket" : classes["InputBoolean"],
  525. "HideSocket" : classes["InputBoolean"],
  526. #
  527. "DriverSocket" : None,
  528. "DriverVariableSocket" : None,
  529. "FCurveSocket" : None,
  530. "KeyframeSocket" : None,
  531. "BoneCollectionSocket" : classes["InputString"],
  532. #
  533. "xFormParameterSocket" : None,
  534. "ParameterBoolSocket" : classes["InputBoolean"],
  535. "ParameterIntSocket" : classes["InputFloat"], #TODO: make an Int node for this
  536. "ParameterFloatSocket" : classes["InputFloat"],
  537. "ParameterVectorSocket" : classes["InputVector"],
  538. "ParameterStringSocket" : classes["InputString"],
  539. #
  540. "TransformSpaceSocket" : classes["InputTransformSpace"],
  541. "BooleanSocket" : classes["InputBoolean"],
  542. "BooleanThreeTupleSocket" : classes["InputBooleanThreeTuple"],
  543. "RotationOrderSocket" : classes["InputRotationOrder"],
  544. "QuaternionSocket" : None,
  545. "QuaternionSocketAA" : None,
  546. "UnsignedIntSocket" : classes["InputFloat"],
  547. "IntSocket" : classes["InputFloat"],
  548. "StringSocket" : classes["InputString"],
  549. #
  550. "BoolUpdateParentNode" : classes["InputBoolean"],
  551. "IKChainLengthSocket" : classes["InputFloat"],
  552. "EnumInheritScale" : classes["InputString"],
  553. "EnumRotationMix" : classes["InputString"],
  554. "EnumRotationMixCopyTransforms" : classes["InputString"],
  555. "EnumMaintainVolumeStretchTo" : classes["InputString"],
  556. "EnumRotationStretchTo" : classes["InputString"],
  557. "EnumTrackAxis" : classes["InputString"],
  558. "EnumUpAxis" : classes["InputString"],
  559. "EnumLockAxis" : classes["InputString"],
  560. "EnumLimitMode" : classes["InputString"],
  561. "EnumYScaleMode" : classes["InputString"],
  562. "EnumXZScaleMode" : classes["InputString"],
  563. "EnumCurveSocket" : classes["InputString"],
  564. "EnumMetaRigSocket" : classes["InputString"],
  565. # Deformers
  566. "EnumSkinning" : classes["InputString"],
  567. #
  568. "FloatSocket" : classes["InputFloat"],
  569. "FloatFactorSocket" : classes["InputFloat"],
  570. "FloatPositiveSocket" : classes["InputFloat"],
  571. "FloatAngleSocket" : classes["InputFloat"],
  572. "VectorSocket" : classes["InputVector"],
  573. "VectorEulerSocket" : classes["InputVector"],
  574. "VectorTranslationSocket" : classes["InputVector"],
  575. "VectorScaleSocket" : classes["InputVector"],
  576. # Drivers
  577. "EnumDriverVariableType" : classes["InputString"],
  578. "EnumDriverVariableEvaluationSpace" : classes["InputString"],
  579. "EnumDriverRotationMode" : classes["InputString"],
  580. "EnumDriverType" : classes["InputString"],
  581. "EnumKeyframeInterpTypeSocket" : classes["InputString"],
  582. "EnumKeyframeBezierHandleTypeSocket" : classes["InputString"],
  583. # Math
  584. "MathFloatOperation" : classes["InputString"],
  585. "MathVectorOperation" : classes["InputString"],
  586. "MatrixTransformOperation" : classes["InputString"],
  587. # Schema
  588. "WildcardSocket" : None,
  589. }
  590. return socket_class_map.get(socket.bl_idname, None)
  591. ####################################
  592. # CURVE STUFF
  593. ####################################
  594. def make_perpendicular(v1, v2):
  595. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  596. perpendicular = v2 - projected
  597. return perpendicular
  598. # this stuff could be branchless but I don't use it much TODO
  599. def cap(val, maxValue):
  600. if (val > maxValue):
  601. return maxValue
  602. return val
  603. def capMin(val, minValue):
  604. if (val < minValue):
  605. return minValue
  606. return val
  607. def wrap(min : float, max : float, value: float) -> float:
  608. range = max-min; remainder = value % range
  609. if remainder > max: return min + remainder-max
  610. else: return remainder
  611. def lerpVal(a, b, fac = 0.5):
  612. return a + ( (b-a) * fac)
  613. #wtf this doesn't do anything even remotely similar to wrap
  614. # HACK BAD FIXME UNBREAK ME BAD
  615. # I don't understand what this function does but I am using it in multiple places?
  616. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  617. if (val > maxValue):
  618. return (-1 * ((maxValue - val) + 1))
  619. if ((minValue) and (val < minValue)):
  620. return (val + maxValue)
  621. return val
  622. #TODO clean this up
  623. def extract_spline_suffix(spline_index):
  624. return ".spline."+str(spline_index).zfill(3)+".extracted"
  625. def do_extract_spline(data, spline):
  626. remove_me = []
  627. for other_spline in data.splines:
  628. if other_spline != spline: remove_me.append(other_spline)
  629. while remove_me: data.splines.remove(remove_me.pop())
  630. def extract_spline(curve, spline_index):
  631. """ Given a curve object and spline index, returns a new object
  632. containing only the selcted spline. The new object is bound to
  633. the original curve.
  634. """
  635. if len(curve.data.splines) == 1:
  636. return curve # nothing to do here.
  637. spline_suffix = extract_spline_suffix(spline_index)
  638. from bpy import data
  639. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  640. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  641. # if the data exists, it is probably stale, so delete it and start over.
  642. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  643. data.curves.remove(old_data)
  644. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  645. new_ob.data = new_data
  646. # do not check for index error here, it is the calling function's responsibility
  647. do_extract_spline(new_data, new_data.splines[spline_index])
  648. # Set up a relationship between the new object and the old object
  649. # now, weirdly enough - we can't use parenting very easily because Blender
  650. # defines the parent on a curve relative to the evaluated path animation
  651. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  652. new_ob.constraints.clear(); new_ob.modifiers.clear()
  653. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  654. new_ob.parent=curve
  655. return new_ob
  656. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  657. # we're storing it separately like this to ensure all nodes use the same
  658. # object if they extract the same spline for use by Mantis.
  659. # this should be transparent to the user since it is working around a
  660. # a limitation in Blender.
  661. if ( curve := mContext.b_objects.get(
  662. proto_curve.name+extract_spline_suffix(spline_index))) is None:
  663. curve = extract_spline(proto_curve, spline_index)
  664. mContext.b_objects[curve.name] = curve
  665. return curve
  666. def RibbonMeshEdgeLengths(m, ribbon):
  667. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  668. lengths = []
  669. for i in range( len( tE ) ): #tE and bE are same length
  670. if (c == True):
  671. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  672. else:
  673. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  674. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  675. if (c == True):
  676. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  677. else:
  678. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  679. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  680. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  681. # get the center, edges may not be straight so total length
  682. # of one edge may be more than the ribbon center's length
  683. lengths.append(( v - vNext ).length)
  684. return lengths
  685. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  686. crvRadius = 0
  687. crv.data.offset = 0
  688. if (crv.data.bevel_depth == 0):
  689. crvRadius = crv.data.extrude
  690. else: #Set ribbon from bevel depth
  691. crvRadius = crv.data.bevel_depth
  692. crv.data.bevel_depth = 0
  693. crv.data.extrude = crvRadius
  694. if (crvRadius == 0):
  695. crv.data.extrude = defaultRadius
  696. def SetRibbonData(m, ribbon):
  697. #maybe this could be incorporated into the DetectWireEdges function?
  698. #maybe I can check for closed poly curves here? under what other circumstance
  699. # will I find the ends of the wire have identical coordinates?
  700. ribbonData = []
  701. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  702. #
  703. lengths = RibbonMeshEdgeLengths(m, ribbon)
  704. lengths.append(0)
  705. totalLength = sum(lengths)
  706. # m.calc_normals() #calculate normals
  707. # it appears this has been removed.
  708. for i, (t, b) in enumerate(zip(tE, bE)):
  709. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  710. tNext = tE[ind]; bNext = bE[ind]
  711. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  712. #if this is a circle, the last v in vertData has a length, otherwise 0
  713. return ribbonData, totalLength
  714. def WireMeshEdgeLengths(m, wire):
  715. circle = False
  716. vIndex = wire.copy()
  717. for e in m.edges:
  718. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  719. #this checks for an edge between the first and last vertex in the wire
  720. circle = True
  721. break
  722. lengths = []
  723. for i in range(len(vIndex)):
  724. v = m.vertices[vIndex[i]]
  725. if (circle == True):
  726. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  727. else:
  728. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  729. vNext = m.vertices[vNextInd]
  730. lengths.append(( v.co - vNext.co ).length)
  731. #if this is a circular wire mesh, this should wrap instead of cap
  732. return lengths
  733. def GetDataFromWire(m, wire):
  734. vertData = []
  735. vIndex = wire.copy()
  736. lengths = WireMeshEdgeLengths(m, wire)
  737. lengths.append(0)
  738. totalLength = sum(lengths)
  739. for i, vInd in enumerate(vIndex):
  740. #-1 to avoid IndexError
  741. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  742. vertData.append((vInd, vNext, lengths[i]))
  743. #if this is a circle, the last v in vertData has a length, otherwise 0
  744. return vertData, totalLength
  745. def DetectWireEdges(mesh):
  746. # Returns a list of vertex indices belonging to wire meshes
  747. # NOTE: this assumes a mesh object with only wire meshes
  748. ret = []
  749. import bmesh
  750. bm = bmesh.new()
  751. try:
  752. bm.from_mesh(mesh)
  753. ends = []
  754. for v in bm.verts:
  755. if (len(v.link_edges) == 1):
  756. ends.append(v.index)
  757. for e in bm.edges:
  758. assert (e.is_wire == True),"This function can only run on wire meshes"
  759. if (e.verts[1].index - e.verts[0].index != 1):
  760. ends.append(e.verts[1].index)
  761. ends.append(e.verts[0].index)
  762. for i in range(len(ends)//2): # // is floor division
  763. beg = ends[i*2]
  764. end = ends[(i*2)+1]
  765. indices = [(j + beg) for j in range ((end - beg) + 1)]
  766. ret.append(indices)
  767. finally:
  768. bm.free()
  769. return ret
  770. def FindNearestPointOnWireMesh(m, pointsList):
  771. from mathutils import Vector
  772. from mathutils.geometry import intersect_point_line
  773. from math import sqrt
  774. wires = DetectWireEdges(m)
  775. ret = []
  776. # prevFactor = None
  777. for wire, points in zip(wires, pointsList):
  778. vertData, total_length = GetDataFromWire(m, wire)
  779. factorsOut = []
  780. for p in points:
  781. prevDist = float('inf')
  782. curDist = float('inf')
  783. v1 = None
  784. v2 = None
  785. for i in range(len(vertData) - 1):
  786. #but it shouldn't check the last one
  787. if (p == m.vertices[i].co):
  788. v1 = vertData[i]
  789. v2 = vertData[i+1]
  790. offset = 0
  791. break
  792. else:
  793. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  794. ((m.vertices[vertData[i][1]].co - p).length) )/2
  795. if (curDist < prevDist):
  796. v1 = vertData[i]
  797. v2 = vertData[i+1]
  798. prevDist = curDist
  799. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  800. m.vertices[v2[0]].co)[1]
  801. if (offset < 0):
  802. offset = 0
  803. elif (offset > 1):
  804. offset = 1
  805. # Assume the vertices are in order
  806. v1Length = 0
  807. v2Length = v2[2]
  808. for i in range(v1[0]):
  809. v1Length += vertData[i][2]
  810. factor = ((offset * (v2Length)) + v1Length )/total_length
  811. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  812. factorsOut.append(factor)
  813. ret.append( factorsOut )
  814. return ret
  815. def mesh_from_curve(crv, context, ribbon=True):
  816. """Utility function for converting a mesh to a curve
  817. which will return the correct mesh even with modifiers"""
  818. import bpy
  819. m = None
  820. bevel = crv.data.bevel_depth
  821. extrude = crv.data.extrude
  822. offset = crv.data.offset
  823. try:
  824. if (len(crv.modifiers) > 0):
  825. do_unlink = False
  826. if (not context.scene.collection.all_objects.get(crv.name)):
  827. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  828. do_unlink = True
  829. dg = context.view_layer.depsgraph
  830. # just gonna modify it for now lol
  831. if ribbon:
  832. EnsureCurveIsRibbon(crv)
  833. else:
  834. crv.data.bevel_depth=0
  835. crv.data.extrude=0
  836. crv.data.offset=0
  837. # try:
  838. dg.update()
  839. mOb = crv.evaluated_get(dg)
  840. m = bpy.data.meshes.new_from_object(mOb)
  841. m.name=crv.data.name+'_mesh'
  842. if (do_unlink):
  843. context.collection.objects.unlink(crv)
  844. else: # (ಥ﹏ಥ) why can't I just use this !
  845. # for now I will just do it like this
  846. if ribbon:
  847. EnsureCurveIsRibbon(crv)
  848. else:
  849. crv.data.bevel_depth=0
  850. crv.data.extrude=0
  851. crv.data.offset=0
  852. m = bpy.data.meshes.new_from_object(crv)
  853. finally:
  854. crv.data.bevel_depth = bevel
  855. crv.data.extrude = extrude
  856. crv.data.offset = offset
  857. return m
  858. def DetectRibbon(f, bm, skipMe):
  859. fFirst = f.index
  860. cont = True
  861. circle = False
  862. tEdge, bEdge = [],[]
  863. while (cont == True):
  864. skipMe.add(f.index)
  865. tEdge.append (f.loops[0].vert.index) # top-left
  866. bEdge.append (f.loops[3].vert.index) # bottom-left
  867. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  868. nFaces = nEdge.link_faces
  869. if (len(nFaces) == 1):
  870. cont = False
  871. else:
  872. for nFace in nFaces:
  873. if (nFace != f):
  874. f = nFace
  875. break
  876. if (f.index == fFirst):
  877. cont = False
  878. circle = True
  879. if (cont == False): # we've reached the end, get the last two:
  880. tEdge.append (f.loops[1].vert.index) # top-right
  881. bEdge.append (f.loops[2].vert.index) # bottom-right
  882. # this will create a loop for rings --
  883. # "the first shall be the last and the last shall be first"
  884. return (tEdge,bEdge,circle)
  885. def DetectRibbons(m, fReport = None):
  886. # Returns list of vertex indices belonging to ribbon mesh edges
  887. # NOTE: this assumes a mesh object with only ribbon meshes
  888. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  889. import bmesh
  890. bm = bmesh.new()
  891. bm.from_mesh(m)
  892. mIslands, mIsland = [], []
  893. skipMe = set()
  894. bm.faces.ensure_lookup_table()
  895. #first, get a list of mesh islands
  896. for f in bm.faces:
  897. if (f.index in skipMe):
  898. continue #already done here
  899. checkMe = [f]
  900. while (len(checkMe) > 0):
  901. facesFound = 0
  902. for f in checkMe:
  903. if (f.index in skipMe):
  904. continue #already done here
  905. mIsland.append(f)
  906. skipMe.add(f.index)
  907. for e in f.edges:
  908. checkMe += e.link_faces
  909. if (facesFound == 0):
  910. #this is the last iteration
  911. mIslands.append(mIsland)
  912. checkMe, mIsland = [], []
  913. ribbons = []
  914. skipMe = set() # to store ends already checked
  915. for mIsl in mIslands:
  916. ribbon = None
  917. first = float('inf')
  918. for f in mIsl:
  919. if (f.index in skipMe):
  920. continue #already done here
  921. if (f.index < first):
  922. first = f.index
  923. adjF = 0
  924. for e in f.edges:
  925. adjF+= (len(e.link_faces) - 1)
  926. # every face other than this one is added to the list
  927. if (adjF == 1):
  928. ribbon = (DetectRibbon(f, bm, skipMe) )
  929. break
  930. if (ribbon == None):
  931. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  932. ribbons.append(ribbon)
  933. # print (ribbons)
  934. return ribbons
  935. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  936. #Note, factors list should be equal in length the the number of wires
  937. #Now working for multiple wires, ugly tho
  938. if (ribbons == None):
  939. ribbons = DetectRibbons(m, fReport=fReport)
  940. if (ribbons is None):
  941. if (fReport):
  942. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  943. else:
  944. print ("No ribbon to get data from.")
  945. return None
  946. ret = []
  947. for factors, ribbon in zip(factorsList, ribbons):
  948. points = []
  949. widths = []
  950. normals = []
  951. ribbonData, totalLength = SetRibbonData(m, ribbon)
  952. for fac in factors:
  953. if (fac == 0):
  954. data = ribbonData[0]
  955. curFac = 0
  956. elif (fac == 1):
  957. data = ribbonData[-1]
  958. curFac = 0
  959. else:
  960. targetLength = totalLength * fac
  961. data = ribbonData[0]
  962. curLength = 0
  963. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  964. if (curLength >= targetLength):
  965. break
  966. curLength += length
  967. data = ( (t, b), (tNext, bNext), length,)
  968. targetLengthAtEdge = (curLength - targetLength)
  969. if (targetLength == 0):
  970. curFac = 0
  971. elif (targetLength == totalLength):
  972. curFac = 1
  973. else:
  974. # NOTE: This can be Zero. That should throw an error.
  975. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  976. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  977. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  978. #location
  979. loc1 = (t1.co).lerp(b1.co, 0.5)
  980. loc2 = (t2.co).lerp(b2.co, 0.5)
  981. #width
  982. w1 = (t1.co - b1.co).length/2
  983. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  984. #normal
  985. n1 = (t1.normal).slerp(b1.normal, 0.5)
  986. n2 = (t1.normal).slerp(b2.normal, 0.5)
  987. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  988. curFac = 0
  989. #don't interpolate if at the end of a ribbon that isn't circular
  990. if ( 0 < curFac < 1):
  991. outPoint = loc1.lerp(loc2, curFac)
  992. outNorm = n1.lerp(n2, curFac)
  993. outWidth = w1 + ( (w2-w1) * curFac)
  994. elif (curFac <= 0):
  995. outPoint = loc1.copy()
  996. outNorm = n1
  997. outWidth = w1
  998. elif (curFac >= 1):
  999. outPoint = loc2.copy()
  1000. outNorm = n2
  1001. outWidth = w2
  1002. outPoint = mat @ outPoint
  1003. outNorm.normalize()
  1004. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1005. widths.append ( outWidth )
  1006. normals.append( outNorm )
  1007. ret.append( (points, widths, normals) )
  1008. return ret # this is a list of tuples containing three lists
  1009. #This bisection search is generic, and it searches based on the
  1010. # magnitude of the error, rather than the sign.
  1011. # If the sign of the error is meaningful, a simpler function
  1012. # can be used.
  1013. def do_bisect_search_by_magnitude(
  1014. owner,
  1015. attribute,
  1016. index = None,
  1017. test_function = None,
  1018. modify = None,
  1019. max_iterations = 10000,
  1020. threshold = 0.0001,
  1021. thresh2 = 0.0005,
  1022. context = None,
  1023. update_dg = None,
  1024. ):
  1025. from math import floor
  1026. i = 0; best_so_far = 0; best = float('inf')
  1027. min = 0; center = max_iterations//2; max = max_iterations
  1028. # enforce getting the absolute value, in case the function has sign information
  1029. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1030. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1031. while (i <= max_iterations):
  1032. upper = (max - ((max-center))//2)
  1033. modify(owner, attribute, index, upper, context = context); error1 = test()
  1034. lower = (center - ((center-min))//2)
  1035. modify(owner, attribute, index, lower, context = context); error2 = test()
  1036. if (error1 < error2):
  1037. min = center
  1038. center, check = upper, upper
  1039. error = error1
  1040. else:
  1041. max = center
  1042. center, check = lower, lower
  1043. error = error2
  1044. if (error <= threshold) or (min == max-1):
  1045. break
  1046. if (error < thresh2):
  1047. j = min
  1048. while (j < max):
  1049. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1050. error = test()
  1051. if (error < best):
  1052. best_so_far = j; best = error
  1053. if (error <= threshold):
  1054. break
  1055. j+=1
  1056. else: # loop has completed without finding a solution
  1057. i = best_so_far; error = test()
  1058. modify(owner, attribute, index, best_so_far, context = context)
  1059. break
  1060. if (error < best):
  1061. best_so_far = check; best = error
  1062. i+=1
  1063. if update_dg:
  1064. update_dg.update()
  1065. else: # Loop has completed without finding a solution
  1066. i = best_so_far
  1067. modify(owner, attribute, best_so_far, context = context); i+=1