utilities.py 49 KB

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