utilities.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  1. #fool: should be wrColor like prColor... dumb
  2. def wrapRed(skk): return "\033[91m{}\033[00m".format(skk)
  3. def wrapGreen(skk): return "\033[92m{}\033[00m".format(skk)
  4. def wrapPurple(skk): return "\033[95m{}\033[00m".format(skk)
  5. def wrapWhite(skk): return "\033[97m{}\033[00m".format(skk)
  6. def wrapOrange(skk): return "\033[0;33m{}\033[00m".format(skk)
  7. # these should reimplement the print interface..
  8. def prRed(*args): print (*[wrapRed(arg) for arg in args])
  9. def prGreen(*args): print (*[wrapGreen(arg) for arg in args])
  10. def prPurple(*args): print (*[wrapPurple(arg) for arg in args])
  11. def prWhite(*args): print (*[wrapWhite(arg) for arg in args])
  12. def prOrange(*args): print (*[wrapOrange(arg) for arg in args])
  13. # add THIS to the top of a file for easy access:
  14. # from mantis.utilities import (prRed, prGreen, prPurple, prWhite,
  15. # prOrange,
  16. # wrapRed, wrapGreen, wrapPurple, wrapWhite,
  17. # wrapOrange,)
  18. def float_lerp(a : float, b : float, factor : float) -> float:
  19. return (a * (1.0 - factor)) + (b * factor)
  20. def find_reroute_start_socket(reroute,):
  21. # "BACK" traces back through the tree and returns one socket
  22. # "FORWARD" traces forward through the tree and returns a list of sockets
  23. from ..base_definitions import reroute_cache
  24. from .node_common import GraphError
  25. # We assume the cache is good, the tree is responsible for this
  26. tree = reroute.id_data
  27. tree_cache = reroute_cache.get(tree.name)
  28. cache_item = tree_cache.get(reroute.name)
  29. if not cache_item or not cache_item.source:
  30. raise GraphError(f"There is a missing link in the tree at reroute node: {reroute.name}")
  31. return tree.nodes[cache_item.source[0]].outputs[cache_item.source[1]]
  32. def find_reroute_end_socket(reroute,):
  33. # "BACK" traces back through the tree and returns one socket
  34. # "FORWARD" traces forward through the tree and returns a list of sockets
  35. from ..base_definitions import reroute_cache
  36. from .node_common import GraphError
  37. # We assume the cache is good, the tree is responsible for this
  38. tree = reroute.id_data
  39. tree_cache = reroute_cache.get(tree.name)
  40. cache_item = tree_cache.get(reroute.name); sockets = []
  41. if not cache_item: # I think this is OK, they don't always go somewhere
  42. return # And this FORWARD trace is always a background task
  43. sockets = [ tree.nodes.get(node_name).inputs[socket_index] for \
  44. node_name, socket_index in cache_item.destinations.items()]
  45. return sockets
  46. # this creates fake links that have the same interface as Blender's
  47. # so that I can bypass Reroutes
  48. def clear_reroutes(links):
  49. from ..base_definitions import DummyLink
  50. kept_links = []
  51. for i in range (len(links)):
  52. link = links[i]
  53. to_cls = link.to_socket.node.bl_idname
  54. from_cls = link.from_socket.node.bl_idname
  55. reroute_classes = ["NodeReroute"]
  56. if (to_cls in reroute_classes and
  57. from_cls in reroute_classes):
  58. continue
  59. elif (to_cls in reroute_classes and not
  60. from_cls in reroute_classes):
  61. continue
  62. elif (from_cls in reroute_classes and not
  63. to_cls in reroute_classes):
  64. # from_socket = find_reroute_start_socket(link.from_node)
  65. from ..base_definitions import reroute_cache
  66. from .node_common import GraphError
  67. # We assume the cache is good, the tree is responsible for this
  68. tree = link.from_node.id_data
  69. tree_cache = reroute_cache.get(tree.name)
  70. cache_item = tree_cache.get(link.from_node.name)
  71. if not cache_item or not cache_item.source:
  72. raise GraphError(f"There is a missing link in the tree at reroute node: {link.from_node.name}")
  73. from_socket = tree.nodes[cache_item.source[0]].outputs[cache_item.source[1]]
  74. new_link = DummyLink(from_socket=from_socket,
  75. to_socket=link.to_socket,
  76. from_mantis_node=None,
  77. to_mantis_node=None,
  78. multi_input_sort_id=link.multi_input_sort_id )
  79. kept_links.append(new_link)
  80. else:
  81. kept_links.append(link)
  82. return kept_links
  83. def tree_from_mantis_node(sig, base_tree):
  84. if (sig[0] == 'MANTIS_AUTOGENERATED'):
  85. sig = sig[:-2] # cut off the end part of the signature (because it uses socket.name and socket.identifier)
  86. # this will lead to totally untraceble bugs in the event of a change in how signatures are assigned
  87. tree = base_tree
  88. for i, path_item in enumerate(sig):
  89. if (i == 0) or (i == len(sig) - 1):
  90. continue
  91. tree = tree.nodes.get(path_item).node_tree
  92. return tree
  93. def get_ui_node(sig, base_tree):
  94. return tree_from_mantis_node(sig, base_tree).nodes.get( sig[-1] )
  95. # Function for splitting up
  96. def split_quoted_substrings_to_strings(text):
  97. import re
  98. pattern = r'''(?:"([^"]*)"|'([^']*)'|([^"']+))'''
  99. substrings = [
  100. next(group for group in match.groups() if group is not None)
  101. for match in re.finditer(pattern, text)
  102. ]
  103. return substrings
  104. def set_bone_selection(pose_bone, selection_state):
  105. # in some older blender versions, select was a bone property
  106. if hasattr(pose_bone, 'select'):
  107. pose_bone.select = selection_state
  108. elif hasattr(pose_bone.bone, 'select'):
  109. pose_bone.bone.select = selection_state
  110. ##################################################################################################
  111. # groups and changing sockets -- this is used extensively by Schema.
  112. ##################################################################################################
  113. # store the overlay state of the node's sockets to ensure they don't reset.
  114. # The socket will only be in the overlay map if it is set to use overlay
  115. def get_socket_overlay_info(node):
  116. overlay_state = {} # we only need the inputs for this
  117. for socket in node.inputs:
  118. if hasattr(socket, 'use_overlay') and socket.use_overlay:
  119. overlay_state[socket.identifier] = socket.overlay_text
  120. return overlay_state
  121. # this one returns None if there is an error.
  122. def get_socket_maps(node, force=False):
  123. maps = [{}, {}]
  124. node_collection = ["inputs", "outputs"]
  125. links = ["from_socket", "to_socket"]
  126. for collection, map, linked_socket in zip(node_collection, maps, links):
  127. for sock in getattr(node, collection):
  128. if sock.is_linked:
  129. other_sockets = []
  130. # Sort the links first (in case they are mult-input), because Blender doesn't
  131. links = sorted(list(sock.links), key = lambda l : l.multi_input_sort_id)
  132. # HACK here because Blender will crash if the socket values in the NodeReroute
  133. # are mutated. Because this seems to happen in a deffered way, I can't account
  134. # for it except by checking the node later...
  135. # TODO: The fact that I need this hack means I can probably solve this problem
  136. # for all node types in a safer way, since they may also be dynamic somehow
  137. for l in links:
  138. if "from" in linked_socket and l.from_node.bl_idname == "NodeReroute":
  139. other_sockets.append(l.from_node)
  140. elif "to" in linked_socket and l.to_node.bl_idname == "NodeReroute":
  141. other_sockets.append(l.to_node)
  142. else:
  143. other_sockets.append(getattr(l, linked_socket))
  144. from bpy.types import NodeSocket
  145. keep_sockets=[]
  146. for other_socket in other_sockets.copy():
  147. if isinstance(other_socket, NodeSocket) and \
  148. other_socket.bl_idname == 'NodeSocketUndefined':
  149. continue # this one is bad
  150. keep_sockets.append(other_socket)
  151. map[sock.identifier]= keep_sockets
  152. elif hasattr(sock, "default_value"):
  153. # in blender 5.0 we have to use sock.default_value insted of sock.get("default_value") :/
  154. if sock.bl_idname == "EnumCurveSocket" and sock.default_value is None:
  155. # HACK I need to add this special case because during file-load,
  156. # this value is None and should not be altered until it is set once.
  157. continue
  158. if sock.default_value is not None:
  159. val = getattr(sock, "default_value")
  160. elif "Enum" in sock.bl_idname and isinstance(sock.get("default_value"), int):
  161. continue # for string enum properties that have not yet initialized (at startup)
  162. elif (val := sock.default_value) is not None:
  163. pass
  164. elif not force:
  165. continue
  166. map[sock.identifier]=val
  167. else:
  168. from ..socket_definitions import no_default_value
  169. if sock.bl_idname in no_default_value:
  170. map[sock.identifier]=None
  171. else:
  172. raise RuntimeError(f"ERROR: Could not get socket data for socket of type: {sock.bl_idname}")
  173. return maps
  174. def generate_intervening_reroute(socket, other_socket,):
  175. from bpy.app import version as bpy_version
  176. print ("i have to make a reroute node here lol")
  177. node = socket.node
  178. reroute = node.id_data.nodes.new('NodeReroute')
  179. # NOTE that this doesn't really do a good job of placing it. Whatever.
  180. l = node.id_data.links.new(input=other_socket, output=reroute.inputs[0])
  181. l = node.id_data.links.new(input=reroute.outputs[0], output=socket)
  182. reroute.location = node.location.lerp(other_socket.node.location, 0.25)
  183. if (bpy_version >= (4,4,0)): # correct the reroute color if possible
  184. reroute.socket_idname = other_socket.bl_idname
  185. return l
  186. # this function is completely overloaded with different purposes and code paths
  187. # TODO refactor everything that funnels into this function
  188. # make this stuff simpler.
  189. def do_relink(node, socket, map, in_out='INPUT', parent_name = ''):
  190. if not node.__class__.is_registered_node_type(): return
  191. tree = node.id_data; interface_in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT'
  192. if hasattr(node, "node_tree"):
  193. tree = node.node_tree
  194. interface_in_out=in_out
  195. from bpy.types import NodeSocket, Node
  196. get_string = '__extend__'
  197. if socket: get_string = socket.identifier
  198. from ..base_definitions import SchemaUINode
  199. if (hasattr(node, "node_tree") or isinstance(node, SchemaUINode)) and get_string not in map.keys():
  200. # this happens when we are creating a new node group and need to update it from nothing.
  201. return
  202. val = map[get_string] # this will throw an error if the socket isn't there. Good!
  203. # IF there are multiple links going from one node-socket to this socket, then we have to relink
  204. # every socket but the first one before it can go in
  205. # Counter for every socket starts at 0 and if it is greater than 0, add a reroute intervening
  206. # then decrement the counter while relinking,
  207. socket_counters = {}
  208. if isinstance(val, list):
  209. for sub_val in val:
  210. # this will only happen once because it assigns socket, so it is safe to do in the for loop.
  211. if socket is None:
  212. socket = sub_val; sockets = [socket]
  213. if sub_val.bl_idname == "NodeReroute":
  214. # we have to trace the reroute node...
  215. if in_out == 'INPUT':
  216. socket = find_reroute_start_socket(sub_val); sockets = [socket]
  217. else:
  218. sockets = find_reroute_end_socket(sub_val)
  219. for socket in sockets:
  220. sock_type = socket.interface_type
  221. name = unique_socket_name(node, socket, tree)
  222. if parent_name:
  223. interface_socket = update_interface(tree.interface, name, interface_in_out, sock_type, parent_name)
  224. if in_out =='INPUT':
  225. socket = node.inputs.new(sock_type, name, identifier=interface_socket.identifier)
  226. else:
  227. socket = node.outputs.new(sock_type, name, identifier=interface_socket.identifier)
  228. if parent_name == 'Array': socket.display_shape='SQUARE_DOT'
  229. if parent_name == 'Constant': socket.display_shape='CIRCLE_DOT'
  230. # then move it up and delete the other link.
  231. # this also needs to modify the interface of the node tree.
  232. if isinstance(sub_val, NodeSocket):
  233. counter_id=sub_val.node.name+"::"+sub_val.identifier
  234. l = None
  235. if in_out =='INPUT':
  236. if socket_counters.get(counter_id) is None:
  237. socket_counters[counter_id] = 0
  238. if socket_counters[counter_id] == 0:
  239. l = node.id_data.links.new(input=sub_val, output=socket)
  240. else:
  241. l = generate_intervening_reroute(socket, sub_val)
  242. socket_counters[counter_id] += 1
  243. else:
  244. l = node.id_data.links.new(input=socket, output=sub_val)
  245. if l is None:
  246. raise RuntimeError("Could not create link")
  247. elif isinstance(sub_val, Node):
  248. counter_id=sub_val.name+"::Output"
  249. l = None
  250. # this happens when it is a NodeReroute
  251. if not socket.is_output:
  252. if socket_counters.get(counter_id) is None:
  253. socket_counters[counter_id] = 0
  254. if socket_counters[counter_id] == 0:
  255. l = node.id_data.links.new(input=sub_val.outputs[0], output=socket)
  256. else:
  257. # NOTE maybe this should make another reroute from the source to here instead
  258. l = generate_intervening_reroute(socket, sub_val.outputs[0])
  259. socket_counters[counter_id] += 1
  260. else:
  261. l = node.id_data.links.new(input=socket, output=sub_val.inputs[0])
  262. if l is None:
  263. raise RuntimeError("Could not create link")
  264. else:
  265. raise RuntimeError("Unhandled case in do_relink()")
  266. elif get_string != "__extend__":
  267. if not socket.is_output:
  268. from bpy.app import version as bpy_version
  269. if bpy_version >=(4,5,0): # VERSIONING
  270. # for some reason, this is throwing an error now
  271. from bpy.types import bpy_prop_array
  272. if isinstance(val, bpy_prop_array):
  273. if in_out == "INPUT" and hasattr(socket, 'input') and socket.input == False:
  274. return # doesn't matter, this is a Matrix socket in a bone or something
  275. # raise RuntimeError(
  276. # f"Cannot set property in socket of type {socket.bl_idname} due to bug in Blender: "
  277. # f"{node.id_data.name}:{node.name}:{socket.name} ")
  278. # TODO: report this weird bug!
  279. try:
  280. if socket.bl_idname == 'BooleanThreeTupleSocket':
  281. # it is so annoying that I have to do this
  282. socket.default_value = [bool(val[0]), bool(val[1]), bool(val[2])]
  283. else:
  284. socket.default_value = val
  285. except (AttributeError, ValueError): # must be readonly or maybe it doesn't have a d.v.
  286. pass
  287. def read_schema_type(interface_item):
  288. # VERSIONING CODE
  289. tree=interface_item.id_data
  290. version = tree.mantis_version
  291. old_version = False
  292. if version[0] == 0:
  293. if version[1] < 13: old_version = True
  294. # unfortunately we need to check this stuff for the versioning code to run correctly the first time.
  295. # UNLESS I can find a way to prevent this code from running before versioning
  296. if old_version or (not hasattr(interface_item, 'is_array')):
  297. # it is not a custom interface class and/or the file is old.
  298. if interface_item.parent:
  299. return interface_item.parent.name
  300. else:
  301. if interface_item.is_array:
  302. return 'Array'
  303. if interface_item.is_connection:
  304. return 'Connection'
  305. return 'Constant'
  306. def update_interface(interface, name, in_out, sock_type, parent_name):
  307. from bpy.app import version as bpy_version
  308. if parent_name:
  309. if not (interface_parent := interface.items_tree.get(parent_name)):
  310. interface_parent = interface.new_panel(name=parent_name)
  311. if bpy_version != (4,5,0):
  312. socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  313. else: # blender 4.5.0 LTS, have to workaround a bug!
  314. from ..versioning import workaround_4_5_0_interface_update
  315. socket = workaround_4_5_0_interface_update(tree=interface.id_data, name=name, in_out=in_out,
  316. sock_type=sock_type, parent_name=parent_name, do_parent=True)
  317. match parent_name:
  318. case "Connection":
  319. socket.is_connection=True
  320. case "Array":
  321. socket.is_array=True
  322. if parent_name == 'Connection':
  323. in_out = 'OUTPUT' if in_out == 'INPUT' else 'INPUT' # flip this make sure connections always do both
  324. other_socket = interface.new_socket(name=name,in_out=in_out, socket_type=sock_type, parent=interface_parent)
  325. other_socket.is_connection = True
  326. return socket
  327. else:
  328. raise RuntimeError(wrapRed("Cannot add interface item to tree without specifying type."))
  329. #UGLY BAD REFACTOR
  330. def relink_socket_map_add_socket(node, socket_collection, item, in_out=None,):
  331. from bpy.app import version as bpy_version
  332. # if not in_out: in_out=item.in_out
  333. multi=False
  334. if in_out == 'INPUT' and read_schema_type(item) == 'Array':
  335. multi = True
  336. # have to work around a bug in 4.5.0 that prevents me from declaring custom socket types
  337. # I have arbitrarily chosen to use the NodeSocketGeometry type to signal that this one is affected.
  338. if bpy_version == (4, 5, 0) and item.bl_socket_idname == 'NodeSocketGeometry':
  339. from ..versioning import socket_add_workaround_for_4_5_0_LTS
  340. s = socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi)
  341. else:
  342. s = socket_collection.new(type=item.bl_socket_idname, name=item.name, identifier=item.identifier, use_multi_input=multi)
  343. if hasattr(s, 'default_value') and hasattr(s, 'is_valid_interface_type') and \
  344. s.is_valid_interface_type == True:
  345. if s.bl_idname not in ['MatrixSocket']: # no default value implemented
  346. from bpy.types import bpy_prop_array
  347. from mathutils import Vector
  348. default_value = 'REPORT BUG ON GITLAB' # default to bug string
  349. val_type = type(s.default_value) # why tf can't I match/case here?
  350. if val_type is bool: default_value = item.default_bool
  351. if val_type is int: default_value = item.default_int
  352. if val_type is float: default_value = item.default_float
  353. if val_type is Vector: default_value = item.default_vector
  354. if val_type is str: default_value = item.default_string
  355. if val_type is bpy_prop_array: default_value = item.default_bool_vector
  356. if not s.is_property_readonly("default_value"):
  357. s.default_value = default_value
  358. else: # TODO: make this work with color sets.
  359. print("WARN: Not yet implemented: default values for color sets.")
  360. if read_schema_type(item) == 'Array': s.display_shape = 'SQUARE_DOT'
  361. elif node.bl_idname in ['MantisSchemaGroup'] and read_schema_type(item) == 'Constant':
  362. s.display_shape='CIRCLE_DOT'
  363. return s
  364. # TODO REFACTOR THIS
  365. # I did this awful thing because I needed the above code
  366. # but I have provided this interface to Mantis
  367. # I did not follow the Single Responsibility Principle
  368. # I am now suffering for it, as I rightly deserve.
  369. def relink_socket_map(node, socket_collection, map, item, in_out):
  370. new_socket = relink_socket_map_add_socket(node, socket_collection, item, in_out,)
  371. do_relink(node, new_socket, map, in_out, parent_name=read_schema_type(item))
  372. def unique_socket_name(node, other_socket, tree):
  373. name_stem = other_socket.bl_label; num=0
  374. # if hasattr(other_socket, "default_value"):
  375. # name_stem = type(other_socket.default_value).__name__
  376. for item in tree.interface.items_tree:
  377. if item.item_type == 'PANEL': continue
  378. if other_socket.is_output and item.in_out == 'INPUT': continue
  379. if not other_socket.is_output and item.in_out == 'OUTPUT': continue
  380. if name_stem in item.name: num+=1
  381. name = name_stem + '.' + str(num).zfill(3)
  382. return name
  383. ##############################
  384. # Dealing with Objects
  385. ##############################
  386. # use this to ensure the active object is set back when changing it
  387. def preserve_active_object(func):
  388. def wrapper(*args, **kwargs):
  389. import bpy
  390. original_active = bpy.context.active_object
  391. func(*args, **kwargs)
  392. bpy.context.view_layer.objects.active = original_active
  393. return wrapper
  394. def switch_mode(mode='OBJECT', objects = []):
  395. active = None
  396. if objects:
  397. from bpy import context, ops
  398. active = objects[-1]
  399. context.view_layer.objects.active = active
  400. if (active):
  401. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  402. ops.object.mode_set(mode=mode)
  403. return active
  404. # run this in Object mode, during bFinalize
  405. @preserve_active_object
  406. def bind_modifier_operator(modifier, operator):
  407. # now we have to bind it
  408. ob = modifier.id_data
  409. ob.modifiers.active = modifier
  410. import bpy
  411. bpy.context.view_layer.objects.active = ob
  412. # Context override does not do anything here... it isn't handled in the C code
  413. # I have verified this by building Blender with print statements to debug.
  414. # let's just make sure the target object has its modifiers disabled and update the dg
  415. targ_attr = "target"
  416. if hasattr(modifier, "object"): targ_attr = "object"
  417. target = getattr(modifier, targ_attr)
  418. if target:
  419. prWhite(f"Binding Deformer {modifier.name} to target {target.name}")
  420. operator(modifier=modifier.name)
  421. def get_default_collection(collection_type='WIDGET'):
  422. from ..preferences import get_bl_addon_object
  423. from bpy import data, context
  424. mantis_addon = get_bl_addon_object(raise_error=True)
  425. match collection_type:
  426. case "WIDGET":
  427. default_collection_name=mantis_addon.preferences.WidgetDefaultCollection
  428. case "CURVE":
  429. default_collection_name=mantis_addon.preferences.CurveDefaultCollection
  430. case "ARMATURE":
  431. default_collection_name=mantis_addon.preferences.MetaArmatureDefaultCollection
  432. if default_collection_name:
  433. if not (default_collection := data.collections.get(default_collection_name)):
  434. default_collection = data.collections.new(default_collection_name)
  435. context.scene.collection.children.link(default_collection)
  436. collection = default_collection
  437. else: collection = context.collection
  438. return collection
  439. def import_widget_obj(path,):
  440. from bpy.app import version as bpy_version
  441. from bpy import context, data
  442. from os import path as os_path
  443. file_name = os_path.split(path)[-1]
  444. obj_name = os_path.splitext(file_name)[0]
  445. collection = get_default_collection(collection_type='WIDGET')
  446. if bpy_version < (4,5,0):
  447. original_active = context.active_object
  448. # for blender versions prior to 4.5.0, we have to import with an operator
  449. from bpy.ops import wm as wm_ops
  450. ob_names_before = data.objects.keys()
  451. wm_ops.obj_import(
  452. filepath=path,
  453. check_existing=False,
  454. forward_axis='NEGATIVE_Z',
  455. up_axis='Y',
  456. validate_meshes=True,)
  457. # just make sure the active object doesn't change
  458. context.view_layer.objects.active = original_active
  459. # the below is a HACK... I can find the objects in the .obj file
  460. # by scanning the file for the "o" prefix and checking the name.
  461. # but that may be slow if the obj is big. which would make a bad widget!
  462. ob = None
  463. for ob in data.objects:
  464. if ob.name in ob_names_before: continue
  465. # this is easier than setting the active collection before import.
  466. for other_collection in ob.users_collection:
  467. other_collection.objects.unlink(ob)
  468. from math import pi as PI
  469. from mathutils import Matrix
  470. m = ob.data
  471. for v in m.vertices:
  472. v.co = Matrix.Rotation(PI/2, 4, 'X') @ v.co
  473. collection.objects.link(ob)
  474. return ob # return the first one, that should be the one
  475. else: # no new object was found - fail.
  476. # I don't expect this to happen unless there is an error in the operator.
  477. raise RuntimeError(f"Failed to import {file_name}. This is probably"
  478. "a bug or a corrupted file.")
  479. else:
  480. prWhite(f"INFO: using Geometry Nodes to import {file_name}")
  481. mesh = data.meshes.new(obj_name)
  482. ob = data.objects.new(name=obj_name, object_data=mesh)
  483. # we'll do a geometry nodes import
  484. collection.objects.link(ob)
  485. if (import_modifier := ob.modifiers.get("Import OBJ")) is None:
  486. import_modifier = ob.modifiers.new("Import OBJ", type='NODES')
  487. ng = data.node_groups.get("Import OBJ")
  488. if ng is None:
  489. from .geometry_node_graphgen import gen_import_obj_node_group
  490. ng = gen_import_obj_node_group()
  491. import_modifier.node_group = ng
  492. import_modifier["Socket_0"]=path
  493. return ob
  494. def import_object_from_file(path):
  495. # first let's check to see if we need it.
  496. from os import path as os_path
  497. file_name = os_path.split(path)[-1]
  498. obj_name = os_path.splitext(file_name)[0]
  499. extension = os_path.splitext(file_name)[1]
  500. if extension == '.obj':
  501. return import_widget_obj(path,)
  502. else:
  503. raise RuntimeError(f"Failed to parse filename {path}")
  504. def import_metarig_data(metarig_data : dict, ):
  505. from bpy import data, context
  506. from mathutils import Matrix
  507. from collections import deque
  508. # the metarig data is a dict with a bunch of nodes in it
  509. # start at node 'MANTIS_RESERVED'
  510. armature_data = metarig_data['MANTIS_RESERVED']
  511. children = deque(armature_data["children"].copy())
  512. if (armature := data.armatures.get(armature_data['name'])) is None:
  513. armature = data.armatures.new(armature_data['name'])
  514. # if we need to do anything here...
  515. if (armature_object := data.objects.get(armature_data['name'])) is None:
  516. armature_object = data.objects.new(armature_data['name'], object_data=armature)
  517. armature_object.matrix_world = Matrix(
  518. ( armature_data['matrix'][:4],
  519. armature_data['matrix'][4:8],
  520. armature_data['matrix'][8:12],
  521. armature_data['matrix'][12:16], )
  522. )
  523. prGreen (armature_data['name'])
  524. # have to add it to the view layer to switch modes.
  525. collection = get_default_collection(collection_type="ARMATURE")
  526. collection.objects.link(armature_object)
  527. # we'll do this to ensure it is actually in the scene for the mode switch
  528. context.scene.collection.objects.link(armature_object)
  529. switch_mode('EDIT', objects = [armature_object])
  530. while (children):
  531. child_name = children.pop()
  532. child_data = metarig_data[child_name]
  533. eb = armature.edit_bones.new(name=child_data['name'])
  534. if parent_name := child_data['parent']:
  535. eb.parent = armature.edit_bones[parent_name]
  536. eb.length = child_data['length']
  537. eb.matrix = Matrix(
  538. ( child_data['matrix'][:4],
  539. child_data['matrix'][4:8],
  540. child_data['matrix'][8:12],
  541. child_data['matrix'][12:16], )
  542. )
  543. displacement = eb.matrix.to_3x3().transposed().row[1] * child_data['length']
  544. eb.tail = eb.matrix.decompose()[0] + displacement
  545. children.extendleft (child_data['children'].copy())
  546. switch_mode('OBJECT', objects = [armature_object])
  547. # and now we can remove it from the scene collection, since it is in the Armature collection
  548. context.scene.collection.objects.unlink(armature_object)
  549. # note that this will not correct if the object exists and is wrong.
  550. return armature_object
  551. def import_curve_data_to_object(curve_name, curve_data):
  552. # the curve data will come as a single curve's data
  553. from bpy import data
  554. curve_object = data.objects.new(curve_name, data.curves.new(name=curve_name, type='CURVE'))
  555. curve_object.data.dimensions = '3D'
  556. prGreen (curve_name)
  557. for spline_data in curve_data:
  558. spline = curve_object.data.splines.new(type=spline_data['type'])
  559. points_data = spline_data['points']
  560. points_collection = spline.points
  561. if spline.type == 'BEZIER':
  562. # the points are bez_pts
  563. spline.bezier_points.add(len(points_data)-1)
  564. points_collection = spline.bezier_points
  565. else:
  566. spline.points.add(len(points_data)-1) # it starts with 1 already
  567. for i, point_data in enumerate(points_data):
  568. if spline.type == 'BEZIER':
  569. pt = spline.bezier_points[i]
  570. else:
  571. pt = spline.points[i]
  572. for prop in dir(pt):
  573. if prop == 'w':
  574. continue
  575. if prop == 'co' and spline.type != 'BEZIER':
  576. value = point_data[prop]
  577. pt.co = (value[0], value[1], value[2], point_data['w'])
  578. continue
  579. if prop in point_data.keys():
  580. setattr(pt, prop, point_data[prop])
  581. for prop in dir(spline):
  582. if prop in spline_data.keys():
  583. if prop in ['points', 'type', 'index']: continue
  584. setattr(spline, prop, spline_data[prop])
  585. collection = get_default_collection(collection_type="CURVE")
  586. collection.objects.link(curve_object)
  587. return curve_object
  588. def get_component_library_items(path='ADD_ARMATURE'):
  589. from os import path as os_path
  590. from ..preferences import get_bl_addon_object
  591. bl_mantis_addon = get_bl_addon_object()
  592. return_value=[]
  593. if bl_mantis_addon:
  594. match path:
  595. case 'ADD_ARMATURE':
  596. components_path = bl_mantis_addon.preferences.ComponentsLibraryFolder
  597. case 'AUTOLOAD':
  598. components_path = bl_mantis_addon.preferences.ComponentsAutoLoadFolder
  599. component_names = {}
  600. from os import walk as os_walk
  601. for path_root, dirs, files, in os_walk(components_path):
  602. for file in files:
  603. relative_file_name = os_path.join(os_path.sep.join(dirs), file)
  604. if file.endswith('.rig'):
  605. component_names[relative_file_name[:-4]] = relative_file_name
  606. if component_names.keys():
  607. for i, (name, path) in enumerate(component_names.items()):
  608. return_value.append( (path, name, path, 'NODE_TREE', i) )
  609. return return_value
  610. ##############################
  611. # READ TREE and also Schema Solve!
  612. ##############################
  613. # TODO: refactor the following two functions, they should be one function with arguments.
  614. def init_connections(mantis_node):
  615. c, hc = [], []
  616. for i in mantis_node.outputs.values():
  617. for l in i.links:
  618. # if l.from_node != mantis_node:
  619. # continue
  620. if l.is_hierarchy:
  621. hc.append(l.to_node)
  622. c.append(l.to_node)
  623. mantis_node.hierarchy_connections = hc
  624. mantis_node.connections = c
  625. def init_dependencies(mantis_node):
  626. c, hc = [], []
  627. for i in mantis_node.inputs.values():
  628. for l in i.links:
  629. # if l.to_node != mantis_node:
  630. # continue
  631. if l.is_hierarchy:
  632. hc.append(l.from_node)
  633. c.append(l.from_node)
  634. mantis_node.hierarchy_dependencies = hc
  635. mantis_node.dependencies = c
  636. def schema_dependency_handle_item(schema, all_mantis_nodes, item,):
  637. hierarchy = True
  638. from ..base_definitions import from_name_filter, to_name_filter
  639. if item.in_out == 'INPUT':
  640. dependencies = schema.dependencies
  641. hierarchy_dependencies = schema.hierarchy_dependencies
  642. parent_name = read_schema_type(item)
  643. if parent_name == 'Array':
  644. for schema_idname in ['SchemaArrayInput', 'SchemaArrayInputGet', 'SchemaArrayInputAll']:
  645. if (mantis_node := all_mantis_nodes.get( (*schema.signature, schema_idname) )):
  646. for to_link in mantis_node.outputs[item.name].links:
  647. if to_link.to_socket in to_name_filter:
  648. # hierarchy_reason='a'
  649. hierarchy = False
  650. for from_link in schema.inputs[item.identifier].links:
  651. if from_link.from_socket in from_name_filter:
  652. hierarchy = False
  653. # hierarchy_reason='b'
  654. if from_link.from_node not in dependencies:
  655. if hierarchy:
  656. hierarchy_dependencies.append(from_link.from_node)
  657. dependencies.append(from_link.from_node)
  658. if parent_name == 'Constant':
  659. if mantis_node := all_mantis_nodes.get((*schema.signature, 'SchemaConstInput')):
  660. for to_link in mantis_node.outputs[item.name].links:
  661. if to_link.to_socket in to_name_filter:
  662. # hierarchy_reason='dependencies'
  663. hierarchy = False
  664. for from_link in schema.inputs[item.identifier].links:
  665. if from_link.from_socket in from_name_filter:
  666. # hierarchy_reason='d'
  667. hierarchy = False
  668. if from_link.from_node not in dependencies:
  669. if hierarchy:
  670. hierarchy_dependencies.append(from_link.from_node)
  671. dependencies.append(from_link.from_node)
  672. if parent_name == 'Connection':
  673. if mantis_node := all_mantis_nodes.get((*schema.signature, 'SchemaIncomingConnection')):
  674. for to_link in mantis_node.outputs[item.name].links:
  675. if to_link.to_socket in to_name_filter:
  676. # hierarchy_reason='e'
  677. hierarchy = False
  678. for from_link in schema.inputs[item.identifier].links:
  679. if from_link.from_socket in from_name_filter:
  680. # hierarchy_reason='f'
  681. hierarchy = False
  682. if from_link.from_node not in dependencies:
  683. if hierarchy:
  684. hierarchy_dependencies.append(from_link.from_node)
  685. dependencies.append(from_link.from_node)
  686. def init_schema_dependencies(schema, all_mantis_nodes):
  687. """ Initialize the dependencies for Schema, and mark them as hierarchy or non-hierarchy dependencies
  688. Non-hierarchy dependencies are e.g. drivers and custom transforms.
  689. """
  690. tree = schema.ui_node.node_tree
  691. if tree is None:
  692. raise RuntimeError(f"Cannot get dependencies for schema {schema}")
  693. schema.dependencies = []
  694. schema.hierarchy_dependencies = []
  695. for l in schema.inputs["Schema Length"].links:
  696. schema.hierarchy_dependencies.append(l.from_node)
  697. if tree.interface:
  698. for item in tree.interface.items_tree:
  699. if item.item_type == 'PANEL':
  700. continue
  701. schema_dependency_handle_item(schema, all_mantis_nodes, item,)
  702. def check_and_add_root(n, roots, include_non_hierarchy=False):
  703. if (include_non_hierarchy * len(n.dependencies)) > 0:
  704. return
  705. elif len(n.hierarchy_dependencies) > 0:
  706. return
  707. roots.append(n)
  708. def get_link_in_out(link):
  709. from ..base_definitions import replace_types
  710. from_name, to_name = link.from_socket.node.name, link.to_socket.node.name
  711. # catch special bl_idnames and bunch the connections up
  712. if link.from_socket.node.bl_idname in replace_types:
  713. from_name = link.from_socket.node.bl_idname
  714. if link.to_socket.node.bl_idname in replace_types:
  715. to_name = link.to_socket.node.bl_idname
  716. return from_name, to_name
  717. def link_mantis_nodes(tree_path_names, link, local_mantis_nodes, from_suffix='', to_suffix=''):
  718. links = clear_reroutes([link])
  719. if links:
  720. link = links[0]
  721. else:
  722. return
  723. dummy_types = ["DUMMY", "DUMMY_SCHEMA"]
  724. from_name, to_name = get_link_in_out(link)
  725. from_mantis_node = local_mantis_nodes.get( (*tree_path_names, from_name+from_suffix) )
  726. to_mantis_node = local_mantis_nodes.get( (*tree_path_names, to_name+to_suffix))
  727. if (from_mantis_node and to_mantis_node):
  728. from_s, to_s = link.from_socket.name, link.to_socket.name
  729. if to_mantis_node.node_type in dummy_types: to_s = link.to_socket.identifier
  730. if from_mantis_node.node_type in dummy_types: from_s = link.from_socket.identifier
  731. try:
  732. connection = from_mantis_node.outputs[from_s].connect(node=to_mantis_node, socket=to_s, sort_id=link.multi_input_sort_id)
  733. if connection is None:
  734. prWhite(f"Already connected: {from_name}:{from_s}->{to_name}:{to_s}")
  735. return connection
  736. except KeyError as e:
  737. prRed(f"{from_mantis_node}:{from_s} or {to_mantis_node}:{to_s} missing; review the connections printed below:")
  738. print (from_mantis_node.outputs.keys())
  739. print (to_mantis_node.inputs.keys())
  740. raise e
  741. else:
  742. prRed(from_mantis_node, to_mantis_node, (*tree_path_names, from_name+from_suffix), (*tree_path_names, to_name+to_suffix))
  743. if to_mantis_node is None:
  744. prRed( "Error: mantis node with signature "
  745. f"{(*tree_path_names, to_name+to_suffix)} "
  746. "does not exist.")
  747. if from_mantis_node is None:
  748. prRed("Error: mantis node with signature "
  749. f"{(*tree_path_names, from_name+from_suffix)} "
  750. "does not exist.")
  751. raise RuntimeError(wrapRed(f"Link not connected: {from_mantis_node} -> {to_mantis_node} in tree" ))
  752. def get_all_dependencies(mantis_node):
  753. from ..base_definitions import GraphError
  754. """ find all dependencies for a mantis node"""
  755. nodes = []
  756. check_nodes = [mantis_node]
  757. nodes_checked = set()
  758. while (len(check_nodes) > 0):
  759. node = check_nodes.pop()
  760. nodes_checked.add (node)
  761. connected_nodes = node.hierarchy_dependencies
  762. for new_node in connected_nodes:
  763. if new_node in nodes:
  764. continue
  765. nodes.append(new_node)
  766. if new_node not in nodes_checked:
  767. check_nodes.append(new_node)
  768. return nodes
  769. def get_all_nodes_of_type(base_tree, bl_idname):
  770. nodes = []
  771. check_nodes = list(base_tree.nodes)
  772. while (len(check_nodes) > 0):
  773. node = check_nodes.pop()
  774. if node.bl_idname in bl_idname:
  775. nodes.append(node)
  776. if hasattr(node, "node_tree"):
  777. check_nodes.extend(list(node.node_tree.nodes))
  778. return nodes
  779. def trace_all_nodes_from_root(root, nodes):
  780. from ..base_definitions import GraphError
  781. """ find all dependencies for a mantis node"""
  782. nodes.add(root); check_nodes = [root]
  783. nodes_checked = set()
  784. while (len(check_nodes) > 0):
  785. node = check_nodes.pop(); nodes_checked.add (node)
  786. connected_nodes = []
  787. for output in node.outputs:
  788. for l in output.links:
  789. if l.to_node not in nodes:
  790. connected_nodes.append(l.to_node)
  791. for new_node in connected_nodes:
  792. nodes.add(new_node)
  793. if new_node not in nodes_checked:
  794. check_nodes.append(new_node)
  795. return nodes
  796. ##################################################################################################
  797. # misc
  798. ##################################################################################################
  799. def all_trees_in_tree(base_tree, selected=False):
  800. """ Recursively finds all trees referenced in a given base-tree."""
  801. # note that this is recursive but not by tail-end recursion
  802. # a while-loop is a better way to do recursion in Python.
  803. trees = [base_tree]
  804. can_descend = True
  805. check_trees = [base_tree]
  806. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  807. new_trees = []
  808. while (len(check_trees) > 0):
  809. tree = check_trees.pop()
  810. for node in tree.nodes:
  811. if selected == True and node.select == False:
  812. continue
  813. if new_tree := getattr(node, "node_tree", None):
  814. if new_tree in trees: continue
  815. new_trees.append(new_tree)
  816. trees.append(new_tree)
  817. check_trees = new_trees
  818. return trees
  819. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  820. def SugiyamaGraph(tree, iterations):
  821. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  822. class defaultview(object):
  823. w,h = 1,1
  824. xz = (0,0)
  825. graph = Graph()
  826. no_links = set()
  827. verts = {}
  828. for n in tree.nodes:
  829. if n.select == True:
  830. v = Vertex(n.name)
  831. v.view = defaultview()
  832. v.view.xy = n.location
  833. v.view.h = n.height*2.5
  834. v.view.w = n.width*2.2
  835. verts[n.name] = v
  836. no_links.add(n.name)
  837. graph.add_vertex(v)
  838. n.select=False
  839. edges = []
  840. inverted_edges=[]
  841. not_a_root = set()
  842. for link in tree.links:
  843. if (link.from_node.name not in verts.keys()) or (link.to_node.name not in verts.keys()):
  844. continue # problem??
  845. weight = 1 # maybe this is useful
  846. not_a_root.add(link.to_node.name) # if it has a edge-input it is not a root.
  847. e = Edge(verts[link.from_node.name], verts[link.to_node.name], weight)
  848. graph.add_edge(e)
  849. edges.append(e )
  850. if link.is_valid == False:
  851. inverted_edges.append(e)
  852. if link.from_node.name in no_links:
  853. no_links.remove(link.from_node.name)
  854. if link.to_node.name in no_links:
  855. no_links.remove(link.to_node.name)
  856. try:
  857. from grandalf.layouts import SugiyamaLayout
  858. # .C[0] is the first "graph core" that contains a connected graph.
  859. sug = SugiyamaLayout(graph.C[0])
  860. sug.init_all()
  861. sug.draw(iterations)
  862. # Digco is good for small graphs.
  863. # from grandalf.layouts import DigcoLayout
  864. # dco = DigcoLayout(graph.C[0])
  865. # dco.init_all()
  866. # dco.draw(iterations)
  867. except KeyboardInterrupt:
  868. pass # just use what it has calculated so far, I guess
  869. for v in graph.C[0].sV:
  870. for n in tree.nodes:
  871. if n.name == v.data:
  872. n.location.x = v.view.xy[1]
  873. n.location.y = v.view.xy[0]
  874. n.select = True
  875. # now we can take all the input nodes and try to put them in a sensible place
  876. # not sure why but this absolutely does not do anything
  877. for n_name in no_links:
  878. n = tree.nodes.get(n_name)
  879. next_node = None
  880. for output in n.outputs:
  881. if output.is_linked == True:
  882. next_node = output.links[0].to_node
  883. break
  884. # let's see if the next node
  885. if next_node:
  886. # need to find the other node in the same layer...
  887. other_node = None
  888. for s_input in next_node.inputs:
  889. if s_input.is_linked:
  890. other_node = s_input.links[0].from_node
  891. if other_node is n:
  892. continue
  893. else:
  894. break
  895. if other_node:
  896. n.location = other_node.location
  897. n.location.y -= other_node.height*2
  898. else: # we'll just position it next to the next node
  899. n.location = next_node.location
  900. n.location.x -= next_node.width*1.5
  901. def project_point_to_plane(point, origin, normal):
  902. return point - normal.dot(point- origin)*normal
  903. ####################################
  904. # CURVE STUFF
  905. ####################################
  906. def make_perpendicular(v1, v2):
  907. from ..base_definitions import FLOAT_EPSILON
  908. if (v1.length_squared < FLOAT_EPSILON) or (v2.length_squared < FLOAT_EPSILON):
  909. raise RuntimeError("Cannot generate perpendicular vetor for zero-length vector")
  910. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  911. perpendicular = v2 - projected
  912. return perpendicular
  913. # this stuff could be branchless but I don't use it much TODO
  914. def cap(val, maxValue):
  915. if (val > maxValue):
  916. return maxValue
  917. return val
  918. def capMin(val, minValue):
  919. if (val < minValue):
  920. return minValue
  921. return val
  922. def wrap(min : float, max : float, value: float) -> float:
  923. range = max-min; remainder = value % range
  924. if remainder > max: return min + remainder-max
  925. else: return remainder
  926. def lerpVal(a, b, fac = 0.5):
  927. return a + ( (b-a) * fac)
  928. #wtf this doesn't do anything even remotely similar to wrap
  929. # HACK BAD FIXME UNBREAK ME BAD
  930. # I don't understand what this function does but I am using it in multiple places?
  931. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  932. if (val > maxValue):
  933. return (-1 * ((maxValue - val) + 1))
  934. if ((minValue) and (val < minValue)):
  935. return (val + maxValue)
  936. return val
  937. #TODO clean this up
  938. def extract_spline_suffix(spline_index):
  939. return ".spline."+str(spline_index).zfill(3)+".extracted"
  940. def do_extract_spline(data, spline):
  941. remove_me = []
  942. for other_spline in data.splines:
  943. if other_spline != spline: remove_me.append(other_spline)
  944. while remove_me: data.splines.remove(remove_me.pop())
  945. def extract_spline(curve, spline_index):
  946. """ Given a curve object and spline index, returns a new object
  947. containing only the selcted spline. The new object is bound to
  948. the original curve.
  949. """
  950. if len(curve.data.splines) == 1:
  951. return curve # nothing to do here.
  952. spline_suffix = extract_spline_suffix(spline_index)
  953. from bpy import data
  954. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  955. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  956. # if the data exists, it is probably stale, so delete it and start over.
  957. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  958. data.curves.remove(old_data)
  959. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  960. new_ob.data = new_data
  961. # do not check for index error here, it is the calling function's responsibility
  962. do_extract_spline(new_data, new_data.splines[spline_index])
  963. return new_ob
  964. def bind_extracted_spline_to_curve(new_ob, curve):
  965. # Set up a relationship between the new object and the old object
  966. # now, weirdly enough - we can't use parenting very easily because Blender
  967. # defines the parent on a curve relative to the evaluated path animation
  968. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  969. from ..xForm_nodes import reset_object_data
  970. reset_object_data(new_ob)
  971. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  972. new_ob.parent=curve
  973. return new_ob
  974. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  975. # we're storing it separately like this to ensure all nodes use the same
  976. # object if they extract the same spline for use by Mantis.
  977. # this should be transparent to the user since it is working around a
  978. # a limitation in Blender.
  979. extracted_spline_name = proto_curve.name+extract_spline_suffix(spline_index)
  980. if curve := mContext.b_objects.get(extracted_spline_name):
  981. return curve
  982. else:
  983. curve = extract_spline(proto_curve, spline_index)
  984. if curve.name != proto_curve.name: # if there is only one spline, no
  985. bind_extracted_spline_to_curve(curve, proto_curve)# dupe is created.
  986. mContext.b_objects[extracted_spline_name] = curve
  987. return curve
  988. def nurbs_copy_bez_spline(curve, bez_spline, do_setup=True):
  989. other_spline= curve.data.splines.new('NURBS')
  990. other_spline.use_endpoint_u=True
  991. other_spline.use_bezier_u=True
  992. bez_pts = bez_spline.bezier_points
  993. bez_data=[]
  994. for i, bez_pt in enumerate(bez_pts):
  995. if i > 0:
  996. bez_data.append(bez_pt.handle_left.copy())
  997. bez_data.append(bez_pt.co.copy())
  998. if i != len(bez_pts)-1:
  999. bez_data.append(bez_pt.handle_right.copy())
  1000. other_spline.points.add(len(bez_data)-1)
  1001. for i, pt in enumerate(bez_data):
  1002. other_spline.points[i].co=(*pt,1.0) # add the W value here
  1003. if do_setup: # do the stuff that makes it behave the same as a bez spline
  1004. other_spline.use_endpoint_u = True; other_spline.use_bezier_u = True
  1005. other_spline.order_u=4 # set to 1 for poly
  1006. return other_spline
  1007. def RibbonMeshEdgeLengths(m, ribbon):
  1008. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  1009. lengths = []
  1010. for i in range( len( tE ) ): #tE and bE are same length
  1011. if (c == True):
  1012. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  1013. else:
  1014. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  1015. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  1016. if (c == True):
  1017. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  1018. else:
  1019. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  1020. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  1021. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  1022. # get the center, edges may not be straight so total length
  1023. # of one edge may be more than the ribbon center's length
  1024. lengths.append(( v - vNext ).length)
  1025. return lengths
  1026. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  1027. from ..base_definitions import FLOAT_EPSILON
  1028. crvRadius = 0
  1029. crv.data.offset = 0
  1030. if (crv.data.bevel_depth < FLOAT_EPSILON):
  1031. crvRadius = crv.data.extrude
  1032. else: #Set ribbon from bevel depth
  1033. crvRadius = crv.data.bevel_depth
  1034. crv.data.bevel_depth = 0
  1035. crv.data.extrude = crvRadius
  1036. if (crvRadius < FLOAT_EPSILON):
  1037. crv.data.extrude = defaultRadius
  1038. def SetRibbonData(m, ribbon):
  1039. #maybe this could be incorporated into the DetectWireEdges function?
  1040. #maybe I can check for closed poly curves here? under what other circumstance
  1041. # will I find the ends of the wire have identical coordinates?
  1042. ribbonData = []
  1043. tE = ribbon[0].copy(); bE = ribbon[1].copy()
  1044. lengths = RibbonMeshEdgeLengths(m, ribbon)
  1045. lengths.append(0)
  1046. totalLength = sum(lengths)
  1047. for i, (t, b) in enumerate(zip(tE, bE)):
  1048. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  1049. tNext = tE[ind]; bNext = bE[ind]
  1050. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  1051. #if this is a circle, the last v in vertData has a length, otherwise 0
  1052. return ribbonData, totalLength
  1053. def WireMeshEdgeLengths(m, wire):
  1054. circle = False
  1055. vIndex = wire.copy()
  1056. for e in m.edges:
  1057. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  1058. #this checks for an edge between the first and last vertex in the wire
  1059. circle = True
  1060. break
  1061. lengths = []
  1062. for i in range(len(vIndex)):
  1063. v = m.vertices[vIndex[i]]
  1064. if (circle == True):
  1065. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  1066. else:
  1067. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  1068. vNext = m.vertices[vNextInd]
  1069. lengths.append(( v.co - vNext.co ).length)
  1070. #if this is a circular wire mesh, this should wrap instead of cap
  1071. return lengths
  1072. def GetDataFromWire(m, wire):
  1073. vertData = []
  1074. vIndex = wire.copy()
  1075. lengths = WireMeshEdgeLengths(m, wire)
  1076. lengths.append(0)
  1077. totalLength = sum(lengths)
  1078. for i, vInd in enumerate(vIndex):
  1079. #-1 to avoid IndexError
  1080. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  1081. vertData.append((vInd, vNext, lengths[i]))
  1082. #if this is a circle, the last v in vertData has a length, otherwise 0
  1083. return vertData, totalLength
  1084. def DetectWireEdges(mesh):
  1085. # Returns a list of vertex indices belonging to wire meshes
  1086. # NOTE: this assumes a mesh object with only wire meshes
  1087. ret = []
  1088. import bmesh
  1089. bm = bmesh.new()
  1090. try:
  1091. bm.from_mesh(mesh)
  1092. ends = []
  1093. for v in bm.verts:
  1094. if (len(v.link_edges) == 1):
  1095. ends.append(v.index)
  1096. for e in bm.edges:
  1097. assert (e.is_wire == True),"This function can only run on wire meshes"
  1098. if (e.verts[1].index - e.verts[0].index != 1):
  1099. ends.append(e.verts[1].index)
  1100. ends.append(e.verts[0].index)
  1101. for i in range(len(ends)//2): # // is floor division
  1102. beg = ends[i*2]
  1103. end = ends[(i*2)+1]
  1104. indices = [(j + beg) for j in range ((end - beg) + 1)]
  1105. ret.append(indices)
  1106. finally:
  1107. bm.free()
  1108. return ret
  1109. def FindNearestPointOnWireMesh(m, pointsList):
  1110. from mathutils import Vector
  1111. from mathutils.geometry import intersect_point_line
  1112. from math import sqrt
  1113. wires = DetectWireEdges(m)
  1114. ret = []
  1115. # prevFactor = None
  1116. for wire, points in zip(wires, pointsList):
  1117. vertData, total_length = GetDataFromWire(m, wire)
  1118. factorsOut = []
  1119. for p in points:
  1120. prevDist = float('inf')
  1121. curDist = float('inf')
  1122. v1 = None
  1123. v2 = None
  1124. for i in range(len(vertData) - 1):
  1125. #but it shouldn't check the last one
  1126. if (p == m.vertices[i].co):
  1127. v1 = vertData[i]
  1128. v2 = vertData[i+1]
  1129. offset = 0
  1130. break
  1131. else:
  1132. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  1133. ((m.vertices[vertData[i][1]].co - p).length) )/2
  1134. if (curDist < prevDist):
  1135. v1 = vertData[i]
  1136. v2 = vertData[i+1]
  1137. prevDist = curDist
  1138. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  1139. m.vertices[v2[0]].co)[1]
  1140. if (offset < 0):
  1141. offset = 0
  1142. elif (offset > 1):
  1143. offset = 1
  1144. # Assume the vertices are in order
  1145. v1Length = 0
  1146. v2Length = v2[2]
  1147. for i in range(v1[0]):
  1148. v1Length += vertData[i][2]
  1149. factor = ((offset * (v2Length)) + v1Length )/total_length
  1150. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  1151. factorsOut.append(factor)
  1152. ret.append( factorsOut )
  1153. return ret
  1154. def mesh_from_curve(crv, context, ribbon=True):
  1155. """Utility function for converting a mesh to a curve
  1156. which will return the correct mesh even with modifiers"""
  1157. import bpy
  1158. m = None
  1159. crv_ob = crv.copy()
  1160. crv_data_copy = crv.data.copy()
  1161. crv_ob.data = crv_data_copy
  1162. if (len(crv_ob.modifiers) > 0):
  1163. do_unlink = False
  1164. if (not context.scene.collection.all_objects.get(crv_ob.name)):
  1165. context.collection.objects.link(crv_ob) # i guess this forces the dg to update it?
  1166. do_unlink = True
  1167. dg = context.view_layer.depsgraph
  1168. # just gonna modify it for now lol
  1169. if ribbon:
  1170. EnsureCurveIsRibbon(crv_ob)
  1171. else:
  1172. crv_ob.data.bevel_depth=0
  1173. crv_ob.data.extrude=0
  1174. crv_ob.data.offset=0
  1175. # try:
  1176. dg.update()
  1177. mOb = crv_ob.evaluated_get(dg)
  1178. m = bpy.data.meshes.new_from_object(mOb)
  1179. m.name=crv_ob.data.name+'_mesh'
  1180. if (do_unlink):
  1181. context.collection.objects.unlink(crv_ob)
  1182. else: # (ಥ﹏ಥ) why can't I just use this !
  1183. # for now I will just do it like this
  1184. if ribbon:
  1185. EnsureCurveIsRibbon(crv_ob)
  1186. else:
  1187. crv_ob.data.bevel_depth=0
  1188. crv_ob.data.extrude=0
  1189. crv_ob.data.offset=0
  1190. m = bpy.data.meshes.new_from_object(crv_ob)
  1191. bpy.data.objects.remove(crv_ob)
  1192. return m
  1193. def DetectRibbon(f, bm, skipMe):
  1194. fFirst = f.index
  1195. cont = True
  1196. circle = False
  1197. tEdge, bEdge = [],[]
  1198. while (cont == True):
  1199. skipMe.add(f.index)
  1200. tEdge.append (f.loops[0].vert.index) # top-left
  1201. bEdge.append (f.loops[3].vert.index) # bottom-left
  1202. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  1203. nFaces = nEdge.link_faces
  1204. if (len(nFaces) == 1):
  1205. cont = False
  1206. else:
  1207. for nFace in nFaces:
  1208. if (nFace != f):
  1209. f = nFace
  1210. break
  1211. if (f.index == fFirst):
  1212. cont = False
  1213. circle = True
  1214. if (cont == False): # we've reached the end, get the last two:
  1215. tEdge.append (f.loops[1].vert.index) # top-right
  1216. bEdge.append (f.loops[2].vert.index) # bottom-right
  1217. # this will create a loop for rings --
  1218. # "the first shall be the last and the last shall be first"
  1219. return (tEdge,bEdge,circle)
  1220. def DetectRibbons(m, fReport = None):
  1221. # Returns list of vertex indices belonging to ribbon mesh edges
  1222. # NOTE: this assumes a mesh object with only ribbon meshes
  1223. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  1224. import bmesh
  1225. bm = bmesh.new()
  1226. bm.from_mesh(m)
  1227. mIslands, mIsland = [], []
  1228. skipMe = set()
  1229. bm.faces.ensure_lookup_table()
  1230. #first, get a list of mesh islands
  1231. for f in bm.faces:
  1232. if (f.index in skipMe):
  1233. continue #already done here
  1234. checkMe = [f]
  1235. while (len(checkMe) > 0):
  1236. facesFound = 0
  1237. for f in checkMe:
  1238. if (f.index in skipMe):
  1239. continue #already done here
  1240. mIsland.append(f)
  1241. skipMe.add(f.index)
  1242. for e in f.edges:
  1243. checkMe += e.link_faces
  1244. if (facesFound == 0):
  1245. #this is the last iteration
  1246. mIslands.append(mIsland)
  1247. checkMe, mIsland = [], []
  1248. ribbons = []
  1249. skipMe = set() # to store ends already checked
  1250. for mIsl in mIslands:
  1251. ribbon = None
  1252. first = float('inf')
  1253. for f in mIsl:
  1254. if (f.index in skipMe):
  1255. continue #already done here
  1256. if (f.index < first):
  1257. first = f.index
  1258. adjF = 0
  1259. for e in f.edges:
  1260. adjF+= (len(e.link_faces) - 1)
  1261. # every face other than this one is added to the list
  1262. if (adjF == 1):
  1263. ribbon = (DetectRibbon(f, bm, skipMe) )
  1264. break
  1265. if (ribbon == None):
  1266. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  1267. ribbons.append(ribbon)
  1268. # print (ribbons)
  1269. return ribbons
  1270. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  1271. #Note, factors list should be equal in length the the number of wires
  1272. #Now working for multiple wires, ugly tho
  1273. if (ribbons == None):
  1274. ribbons = DetectRibbons(m, fReport=fReport)
  1275. if (ribbons is None):
  1276. if (fReport):
  1277. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  1278. else:
  1279. print ("No ribbon to get data from.")
  1280. return None
  1281. ret = []
  1282. for factors, ribbon in zip(factorsList, ribbons):
  1283. points = []
  1284. widths = []
  1285. normals = []
  1286. ribbonData, totalLength = SetRibbonData(m, ribbon)
  1287. for fac in factors:
  1288. if (fac == 0):
  1289. data = ribbonData[0]
  1290. curFac = 0
  1291. elif (fac == 1):
  1292. data = ribbonData[-1]
  1293. curFac = 0
  1294. else:
  1295. targetLength = totalLength * fac
  1296. data = ribbonData[0]
  1297. curLength = 0
  1298. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  1299. if (curLength >= targetLength):
  1300. break
  1301. curLength += length
  1302. data = ( (t, b), (tNext, bNext), length,)
  1303. targetLengthAtEdge = (curLength - targetLength)
  1304. if (targetLength == 0):
  1305. curFac = 0
  1306. elif (targetLength == totalLength):
  1307. curFac = 1
  1308. else:
  1309. # NOTE: This can be Zero. Find out why!
  1310. if data[2] == 0:
  1311. curFac=0
  1312. else:
  1313. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  1314. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  1315. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  1316. #location
  1317. loc1 = (t1.co).lerp(b1.co, 0.5)
  1318. loc2 = (t2.co).lerp(b2.co, 0.5)
  1319. #width
  1320. w1 = (t1.co - b1.co).length/2
  1321. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  1322. #normal
  1323. n1 = (t1.normal).slerp(b1.normal, 0.5)
  1324. n2 = (t1.normal).slerp(b2.normal, 0.5)
  1325. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  1326. curFac = 0
  1327. #don't interpolate if at the end of a ribbon that isn't circular
  1328. if ( 0 < curFac < 1):
  1329. outPoint = loc1.lerp(loc2, curFac)
  1330. outNorm = n1.lerp(n2, curFac)
  1331. outWidth = w1 + ( (w2-w1) * curFac)
  1332. elif (curFac <= 0):
  1333. outPoint = loc1.copy()
  1334. outNorm = n1
  1335. outWidth = w1
  1336. elif (curFac >= 1):
  1337. outPoint = loc2.copy()
  1338. outNorm = n2
  1339. outWidth = w2
  1340. outPoint = mat @ outPoint
  1341. outNorm.normalize()
  1342. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1343. widths.append ( outWidth )
  1344. normals.append( outNorm )
  1345. ret.append( (points, widths, normals) )
  1346. return ret # this is a list of tuples containing three lists
  1347. from mathutils import Vector
  1348. # Used for filling the Curve LUTimport numpy as np
  1349. import numpy as np
  1350. def all_data_from_ribbon(mesh, mat, ribbon):
  1351. top_indices, bottom_indices, is_closed = ribbon
  1352. top_indices = np.asarray(top_indices, dtype=np.intp)
  1353. bottom_indices = np.asarray(bottom_indices, dtype=np.intp)
  1354. count = len(top_indices)
  1355. assert count >= 2, "this should never happen, report this as a bug"
  1356. # we'll use numpy to calculate the positions and normals because it is fast.
  1357. vertex_count = len(mesh.vertices)
  1358. coordinates = np.empty(vertex_count * 3, dtype=np.float64)
  1359. mesh.vertices.foreach_get("co", coordinates)
  1360. coordinates = coordinates.reshape((-1, 3))
  1361. vertex_normals = np.empty(vertex_count * 3, dtype=np.float64)
  1362. mesh.vertices.foreach_get("normal", vertex_normals)
  1363. vertex_normals = vertex_normals.reshape((-1, 3))
  1364. top_local = coordinates[top_indices]; bottom_local = coordinates[bottom_indices]
  1365. # similarly we have to make the world matrix a numpy array
  1366. transform = np.asarray(mat, dtype=np.float64)
  1367. basis = transform[:3, :3]; translation = transform[:3, 3]
  1368. #.T is transpose because this numpy array expects row-major
  1369. top_positions = top_local @ basis.T + translation
  1370. bottom_positions = bottom_local @ basis.T + translation
  1371. positions = (top_positions + bottom_positions) * 0.5
  1372. radii = np.linalg.norm(top_positions - bottom_positions, axis=1) * 0.5
  1373. # transform the potisions by the object's matrix, mat
  1374. # and the normals need a slightly different transformation
  1375. normal_transform = np.linalg.inv(basis).T
  1376. local_normals = ( vertex_normals[top_indices] + vertex_normals[bottom_indices] )
  1377. normals = local_normals @ normal_transform.T
  1378. normal_lengths = np.linalg.norm(normals, axis=1)
  1379. # Normalize the normals by dividing them by the lengths. avoid dividing by 0
  1380. normals = np.divide(
  1381. normals,
  1382. normal_lengths[:, None],
  1383. out=np.zeros_like(normals),
  1384. where=normal_lengths[:, None] != 0,
  1385. )
  1386. # all of this incoming/outgoing subtraction stuff is doing the following:
  1387. # take the current vertex positon and get the tangent vector of each segment
  1388. # it is a part of, then average them
  1389. if is_closed: # have to adjust it back, I don't really know if this works
  1390. incoming = positions - np.roll(positions, 1, axis=0)
  1391. outgoing = np.roll(positions, -1, axis=0) - positions
  1392. else:
  1393. incoming = np.zeros_like(positions); outgoing = np.zeros_like(positions)
  1394. incoming[1:] = positions[1:] - positions[:-1]
  1395. outgoing[:-1] = positions[1:] - positions[:-1]
  1396. incoming[0] = outgoing[0]
  1397. outgoing[-1] = incoming[-1]
  1398. incoming_lengths = np.linalg.norm(incoming, axis=1)
  1399. outgoing_lengths = np.linalg.norm(outgoing, axis=1)
  1400. # the segments may be different lengths so we have to normalize them
  1401. incoming = np.divide(
  1402. incoming,
  1403. incoming_lengths[:, None],
  1404. out=np.zeros_like(incoming),
  1405. where=incoming_lengths[:, None] != 0,
  1406. )
  1407. outgoing = np.divide(
  1408. outgoing,
  1409. outgoing_lengths[:, None],
  1410. out=np.zeros_like(outgoing),
  1411. where=outgoing_lengths[:, None] != 0,
  1412. )
  1413. # then we add them together and normalize again to average them
  1414. tangents = incoming + outgoing
  1415. tangent_lengths = np.linalg.norm(tangents, axis=1)
  1416. tangents = np.divide(
  1417. tangents,
  1418. tangent_lengths[:, None],
  1419. out=np.zeros_like(tangents),
  1420. where=tangent_lengths[:, None] != 0,
  1421. )
  1422. # calcualte the U value of the samples based on the length of the spline
  1423. segment_lengths = np.linalg.norm(positions[1:] - positions[:-1], axis=1)
  1424. if is_closed:
  1425. closing_length = np.linalg.norm(positions[0] - positions[-1])
  1426. total_length = segment_lengths.sum() + closing_length
  1427. else:
  1428. total_length = segment_lengths.sum()
  1429. if total_length:
  1430. u_samples = np.concatenate(([0.0], np.cumsum(segment_lengths))) / total_length
  1431. else:
  1432. u_samples = np.zeros(count, dtype=np.float64)
  1433. # now we have to convert the values back to values Blender uses
  1434. # TODO eventually I want to port everything to numpy even tho it is ugly
  1435. u_samples = tuple(u_samples)
  1436. radii = tuple(radii)
  1437. from mathutils import Vector
  1438. positions = [Vector(elem) for elem in positions]
  1439. normals = [Vector(elem) for elem in normals]
  1440. tangents = [Vector(elem) for elem in tangents]
  1441. return u_samples, positions, normals, tangents, radii
  1442. #This bisection search is generic, and it searches based on the
  1443. # magnitude of the error, rather than the sign.
  1444. # If the sign of the error is meaningful, a simpler function
  1445. # can be used.
  1446. def do_bisect_search_by_magnitude(
  1447. owner,
  1448. attribute,
  1449. index = None,
  1450. test_function = None,
  1451. modify = None,
  1452. max_iterations = 10000,
  1453. threshold = 0.0001,
  1454. thresh2 = 0.0005,
  1455. context = None,
  1456. update_dg = None,
  1457. ):
  1458. from math import floor
  1459. i = 0; best_so_far = 0; best = float('inf')
  1460. min = 0; center = max_iterations//2; max = max_iterations
  1461. # enforce getting the absolute value, in case the function has sign information
  1462. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1463. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1464. while (i <= max_iterations):
  1465. upper = (max - ((max-center))//2)
  1466. modify(owner, attribute, index, upper, context = context); error1 = test()
  1467. lower = (center - ((center-min))//2)
  1468. modify(owner, attribute, index, lower, context = context); error2 = test()
  1469. if (error1 < error2):
  1470. min = center
  1471. center, check = upper, upper
  1472. error = error1
  1473. else:
  1474. max = center
  1475. center, check = lower, lower
  1476. error = error2
  1477. if (error <= threshold) or (min == max-1):
  1478. break
  1479. if (error < thresh2):
  1480. j = min
  1481. while (j < max):
  1482. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1483. error = test()
  1484. if (error < best):
  1485. best_so_far = j; best = error
  1486. if (error <= threshold):
  1487. break
  1488. j+=1
  1489. else: # loop has completed without finding a solution
  1490. i = best_so_far; error = test()
  1491. modify(owner, attribute, index, best_so_far, context = context)
  1492. break
  1493. if (error < best):
  1494. best_so_far = check; best = error
  1495. i+=1
  1496. if update_dg:
  1497. update_dg.update()
  1498. else: # Loop has completed without finding a solution
  1499. i = best_so_far
  1500. modify(owner, attribute, best_so_far, context = context); i+=1