utilities.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  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. if bpy_version < (5, 2, 0):
  493. import_modifier["Socket_0"]=path
  494. else:
  495. import_modifier.properties.inputs.Socket_0.value = path
  496. return ob
  497. def import_object_from_file(path):
  498. # first let's check to see if we need it.
  499. from os import path as os_path
  500. file_name = os_path.split(path)[-1]
  501. obj_name = os_path.splitext(file_name)[0]
  502. extension = os_path.splitext(file_name)[1]
  503. if extension == '.obj':
  504. return import_widget_obj(path,)
  505. else:
  506. raise RuntimeError(f"Failed to parse filename {path}")
  507. def import_metarig_data(metarig_data : dict, ):
  508. from bpy import data, context
  509. from mathutils import Matrix
  510. from collections import deque
  511. # the metarig data is a dict with a bunch of nodes in it
  512. # start at node 'MANTIS_RESERVED'
  513. armature_data = metarig_data['MANTIS_RESERVED']
  514. children = deque(armature_data["children"].copy())
  515. if (armature := data.armatures.get(armature_data['name'])) is None:
  516. armature = data.armatures.new(armature_data['name'])
  517. # if we need to do anything here...
  518. if (armature_object := data.objects.get(armature_data['name'])) is None:
  519. armature_object = data.objects.new(armature_data['name'], object_data=armature)
  520. armature_object.matrix_world = Matrix(
  521. ( armature_data['matrix'][:4],
  522. armature_data['matrix'][4:8],
  523. armature_data['matrix'][8:12],
  524. armature_data['matrix'][12:16], )
  525. )
  526. prGreen (armature_data['name'])
  527. # have to add it to the view layer to switch modes.
  528. collection = get_default_collection(collection_type="ARMATURE")
  529. collection.objects.link(armature_object)
  530. # we'll do this to ensure it is actually in the scene for the mode switch
  531. context.scene.collection.objects.link(armature_object)
  532. switch_mode('EDIT', objects = [armature_object])
  533. while (children):
  534. child_name = children.pop()
  535. child_data = metarig_data[child_name]
  536. eb = armature.edit_bones.new(name=child_data['name'])
  537. if parent_name := child_data['parent']:
  538. eb.parent = armature.edit_bones[parent_name]
  539. eb.length = child_data['length']
  540. eb.matrix = Matrix(
  541. ( child_data['matrix'][:4],
  542. child_data['matrix'][4:8],
  543. child_data['matrix'][8:12],
  544. child_data['matrix'][12:16], )
  545. )
  546. displacement = eb.matrix.to_3x3().transposed().row[1] * child_data['length']
  547. eb.tail = eb.matrix.decompose()[0] + displacement
  548. children.extendleft (child_data['children'].copy())
  549. switch_mode('OBJECT', objects = [armature_object])
  550. # and now we can remove it from the scene collection, since it is in the Armature collection
  551. context.scene.collection.objects.unlink(armature_object)
  552. # note that this will not correct if the object exists and is wrong.
  553. return armature_object
  554. def import_curve_data_to_object(curve_name, curve_data):
  555. # the curve data will come as a single curve's data
  556. from bpy import data
  557. curve_object = data.objects.new(curve_name, data.curves.new(name=curve_name, type='CURVE'))
  558. curve_object.data.dimensions = '3D'
  559. prGreen (curve_name)
  560. for spline_data in curve_data:
  561. spline = curve_object.data.splines.new(type=spline_data['type'])
  562. points_data = spline_data['points']
  563. points_collection = spline.points
  564. if spline.type == 'BEZIER':
  565. # the points are bez_pts
  566. spline.bezier_points.add(len(points_data)-1)
  567. points_collection = spline.bezier_points
  568. else:
  569. spline.points.add(len(points_data)-1) # it starts with 1 already
  570. for i, point_data in enumerate(points_data):
  571. if spline.type == 'BEZIER':
  572. pt = spline.bezier_points[i]
  573. else:
  574. pt = spline.points[i]
  575. for prop in dir(pt):
  576. if prop == 'w':
  577. continue
  578. if prop == 'co' and spline.type != 'BEZIER':
  579. value = point_data[prop]
  580. pt.co = (value[0], value[1], value[2], point_data['w'])
  581. continue
  582. if prop in point_data.keys():
  583. setattr(pt, prop, point_data[prop])
  584. for prop in dir(spline):
  585. if prop in spline_data.keys():
  586. if prop in ['points', 'type', 'index']: continue
  587. setattr(spline, prop, spline_data[prop])
  588. collection = get_default_collection(collection_type="CURVE")
  589. collection.objects.link(curve_object)
  590. return curve_object
  591. def get_component_library_items(path='ADD_ARMATURE'):
  592. from os import path as os_path
  593. from ..preferences import get_bl_addon_object
  594. bl_mantis_addon = get_bl_addon_object()
  595. return_value=[]
  596. if bl_mantis_addon:
  597. match path:
  598. case 'ADD_ARMATURE':
  599. components_path = bl_mantis_addon.preferences.ComponentsLibraryFolder
  600. case 'AUTOLOAD':
  601. components_path = bl_mantis_addon.preferences.ComponentsAutoLoadFolder
  602. component_names = {}
  603. from os import walk as os_walk
  604. for path_root, dirs, files, in os_walk(components_path):
  605. for file in files:
  606. relative_file_name = os_path.join(os_path.sep.join(dirs), file)
  607. if file.endswith('.rig'):
  608. component_names[relative_file_name[:-4]] = relative_file_name
  609. if component_names.keys():
  610. for i, (name, path) in enumerate(component_names.items()):
  611. return_value.append( (path, name, path, 'NODE_TREE', i) )
  612. return return_value
  613. ##############################
  614. # READ TREE and also Schema Solve!
  615. ##############################
  616. # TODO: refactor the following two functions, they should be one function with arguments.
  617. def init_connections(mantis_node):
  618. c, hc = [], []
  619. for i in mantis_node.outputs.values():
  620. for l in i.links:
  621. # if l.from_node != mantis_node:
  622. # continue
  623. if l.is_hierarchy:
  624. hc.append(l.to_node)
  625. c.append(l.to_node)
  626. mantis_node.hierarchy_connections = hc
  627. mantis_node.connections = c
  628. def init_dependencies(mantis_node):
  629. c, hc = [], []
  630. for i in mantis_node.inputs.values():
  631. for l in i.links:
  632. # if l.to_node != mantis_node:
  633. # continue
  634. if l.is_hierarchy:
  635. hc.append(l.from_node)
  636. c.append(l.from_node)
  637. mantis_node.hierarchy_dependencies = hc
  638. mantis_node.dependencies = c
  639. def schema_dependency_handle_item(schema, all_mantis_nodes, item,):
  640. hierarchy = True
  641. from ..base_definitions import from_name_filter, to_name_filter
  642. if item.in_out == 'INPUT':
  643. dependencies = schema.dependencies
  644. hierarchy_dependencies = schema.hierarchy_dependencies
  645. parent_name = read_schema_type(item)
  646. if parent_name == 'Array':
  647. for schema_idname in ['SchemaArrayInput', 'SchemaArrayInputGet', 'SchemaArrayInputAll']:
  648. if (mantis_node := all_mantis_nodes.get( (*schema.signature, schema_idname) )):
  649. for to_link in mantis_node.outputs[item.name].links:
  650. if to_link.to_socket in to_name_filter:
  651. # hierarchy_reason='a'
  652. hierarchy = False
  653. for from_link in schema.inputs[item.identifier].links:
  654. if from_link.from_socket in from_name_filter:
  655. hierarchy = False
  656. # hierarchy_reason='b'
  657. if from_link.from_node not in dependencies:
  658. if hierarchy:
  659. hierarchy_dependencies.append(from_link.from_node)
  660. dependencies.append(from_link.from_node)
  661. if parent_name == 'Constant':
  662. if mantis_node := all_mantis_nodes.get((*schema.signature, 'SchemaConstInput')):
  663. for to_link in mantis_node.outputs[item.name].links:
  664. if to_link.to_socket in to_name_filter:
  665. # hierarchy_reason='dependencies'
  666. hierarchy = False
  667. for from_link in schema.inputs[item.identifier].links:
  668. if from_link.from_socket in from_name_filter:
  669. # hierarchy_reason='d'
  670. hierarchy = False
  671. if from_link.from_node not in dependencies:
  672. if hierarchy:
  673. hierarchy_dependencies.append(from_link.from_node)
  674. dependencies.append(from_link.from_node)
  675. if parent_name == 'Connection':
  676. if mantis_node := all_mantis_nodes.get((*schema.signature, 'SchemaIncomingConnection')):
  677. for to_link in mantis_node.outputs[item.name].links:
  678. if to_link.to_socket in to_name_filter:
  679. # hierarchy_reason='e'
  680. hierarchy = False
  681. for from_link in schema.inputs[item.identifier].links:
  682. if from_link.from_socket in from_name_filter:
  683. # hierarchy_reason='f'
  684. hierarchy = False
  685. if from_link.from_node not in dependencies:
  686. if hierarchy:
  687. hierarchy_dependencies.append(from_link.from_node)
  688. dependencies.append(from_link.from_node)
  689. def init_schema_dependencies(schema, all_mantis_nodes):
  690. """ Initialize the dependencies for Schema, and mark them as hierarchy or non-hierarchy dependencies
  691. Non-hierarchy dependencies are e.g. drivers and custom transforms.
  692. """
  693. tree = schema.ui_node.node_tree
  694. if tree is None:
  695. raise RuntimeError(f"Cannot get dependencies for schema {schema}")
  696. schema.dependencies = []
  697. schema.hierarchy_dependencies = []
  698. for l in schema.inputs["Schema Length"].links:
  699. schema.hierarchy_dependencies.append(l.from_node)
  700. if tree.interface:
  701. for item in tree.interface.items_tree:
  702. if item.item_type == 'PANEL':
  703. continue
  704. schema_dependency_handle_item(schema, all_mantis_nodes, item,)
  705. def check_and_add_root(n, roots, include_non_hierarchy=False):
  706. if (include_non_hierarchy * len(n.dependencies)) > 0:
  707. return
  708. elif len(n.hierarchy_dependencies) > 0:
  709. return
  710. roots.append(n)
  711. def get_link_in_out(link):
  712. from ..base_definitions import replace_types
  713. from_name, to_name = link.from_socket.node.name, link.to_socket.node.name
  714. # catch special bl_idnames and bunch the connections up
  715. if link.from_socket.node.bl_idname in replace_types:
  716. from_name = link.from_socket.node.bl_idname
  717. if link.to_socket.node.bl_idname in replace_types:
  718. to_name = link.to_socket.node.bl_idname
  719. return from_name, to_name
  720. def link_mantis_nodes(tree_path_names, link, local_mantis_nodes, from_suffix='', to_suffix=''):
  721. links = clear_reroutes([link])
  722. if links:
  723. link = links[0]
  724. else:
  725. return
  726. dummy_types = ["DUMMY", "DUMMY_SCHEMA"]
  727. from_name, to_name = get_link_in_out(link)
  728. from_mantis_node = local_mantis_nodes.get( (*tree_path_names, from_name+from_suffix) )
  729. to_mantis_node = local_mantis_nodes.get( (*tree_path_names, to_name+to_suffix))
  730. if (from_mantis_node and to_mantis_node):
  731. from_s, to_s = link.from_socket.name, link.to_socket.name
  732. if to_mantis_node.node_type in dummy_types: to_s = link.to_socket.identifier
  733. if from_mantis_node.node_type in dummy_types: from_s = link.from_socket.identifier
  734. try:
  735. connection = from_mantis_node.outputs[from_s].connect(node=to_mantis_node, socket=to_s, sort_id=link.multi_input_sort_id)
  736. if connection is None:
  737. prWhite(f"Already connected: {from_name}:{from_s}->{to_name}:{to_s}")
  738. return connection
  739. except KeyError as e:
  740. prRed(f"{from_mantis_node}:{from_s} or {to_mantis_node}:{to_s} missing; review the connections printed below:")
  741. print (from_mantis_node.outputs.keys())
  742. print (to_mantis_node.inputs.keys())
  743. raise e
  744. else:
  745. prRed(from_mantis_node, to_mantis_node, (*tree_path_names, from_name+from_suffix), (*tree_path_names, to_name+to_suffix))
  746. if to_mantis_node is None:
  747. prRed( "Error: mantis node with signature "
  748. f"{(*tree_path_names, to_name+to_suffix)} "
  749. "does not exist.")
  750. if from_mantis_node is None:
  751. prRed("Error: mantis node with signature "
  752. f"{(*tree_path_names, from_name+from_suffix)} "
  753. "does not exist.")
  754. raise RuntimeError(wrapRed(f"Link not connected: {from_mantis_node} -> {to_mantis_node} in tree" ))
  755. def get_all_dependencies(mantis_node):
  756. from ..base_definitions import GraphError
  757. """ find all dependencies for a mantis node"""
  758. nodes = []
  759. check_nodes = [mantis_node]
  760. nodes_checked = set()
  761. while (len(check_nodes) > 0):
  762. node = check_nodes.pop()
  763. nodes_checked.add (node)
  764. connected_nodes = node.hierarchy_dependencies
  765. for new_node in connected_nodes:
  766. if new_node in nodes:
  767. continue
  768. nodes.append(new_node)
  769. if new_node not in nodes_checked:
  770. check_nodes.append(new_node)
  771. return nodes
  772. def get_all_nodes_of_type(base_tree, bl_idname):
  773. nodes = []
  774. check_nodes = list(base_tree.nodes)
  775. while (len(check_nodes) > 0):
  776. node = check_nodes.pop()
  777. if node.bl_idname in bl_idname:
  778. nodes.append(node)
  779. if hasattr(node, "node_tree"):
  780. check_nodes.extend(list(node.node_tree.nodes))
  781. return nodes
  782. def trace_all_nodes_from_root(root, nodes):
  783. from ..base_definitions import GraphError
  784. """ find all dependencies for a mantis node"""
  785. nodes.add(root); check_nodes = [root]
  786. nodes_checked = set()
  787. while (len(check_nodes) > 0):
  788. node = check_nodes.pop(); nodes_checked.add (node)
  789. connected_nodes = []
  790. for output in node.outputs:
  791. for l in output.links:
  792. if l.to_node not in nodes:
  793. connected_nodes.append(l.to_node)
  794. for new_node in connected_nodes:
  795. nodes.add(new_node)
  796. if new_node not in nodes_checked:
  797. check_nodes.append(new_node)
  798. return nodes
  799. ##################################################################################################
  800. # misc
  801. ##################################################################################################
  802. def all_trees_in_tree(base_tree, selected=False):
  803. """ Recursively finds all trees referenced in a given base-tree."""
  804. # note that this is recursive but not by tail-end recursion
  805. # a while-loop is a better way to do recursion in Python.
  806. trees = [base_tree]
  807. can_descend = True
  808. check_trees = [base_tree]
  809. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  810. new_trees = []
  811. while (len(check_trees) > 0):
  812. tree = check_trees.pop()
  813. for node in tree.nodes:
  814. if selected == True and node.select == False:
  815. continue
  816. if new_tree := getattr(node, "node_tree", None):
  817. if new_tree in trees: continue
  818. new_trees.append(new_tree)
  819. trees.append(new_tree)
  820. check_trees = new_trees
  821. return trees
  822. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  823. def SugiyamaGraph(tree, iterations):
  824. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  825. class defaultview(object):
  826. w,h = 1,1
  827. xz = (0,0)
  828. graph = Graph()
  829. no_links = set()
  830. verts = {}
  831. for n in tree.nodes:
  832. if n.select == True:
  833. v = Vertex(n.name)
  834. v.view = defaultview()
  835. v.view.xy = n.location
  836. v.view.h = n.height*2.5
  837. v.view.w = n.width*2.2
  838. verts[n.name] = v
  839. no_links.add(n.name)
  840. graph.add_vertex(v)
  841. n.select=False
  842. edges = []
  843. inverted_edges=[]
  844. not_a_root = set()
  845. for link in tree.links:
  846. if (link.from_node.name not in verts.keys()) or (link.to_node.name not in verts.keys()):
  847. continue # problem??
  848. weight = 1 # maybe this is useful
  849. not_a_root.add(link.to_node.name) # if it has a edge-input it is not a root.
  850. e = Edge(verts[link.from_node.name], verts[link.to_node.name], weight)
  851. graph.add_edge(e)
  852. edges.append(e )
  853. if link.is_valid == False:
  854. inverted_edges.append(e)
  855. if link.from_node.name in no_links:
  856. no_links.remove(link.from_node.name)
  857. if link.to_node.name in no_links:
  858. no_links.remove(link.to_node.name)
  859. try:
  860. from grandalf.layouts import SugiyamaLayout
  861. # .C[0] is the first "graph core" that contains a connected graph.
  862. sug = SugiyamaLayout(graph.C[0])
  863. sug.init_all()
  864. sug.draw(iterations)
  865. # Digco is good for small graphs.
  866. # from grandalf.layouts import DigcoLayout
  867. # dco = DigcoLayout(graph.C[0])
  868. # dco.init_all()
  869. # dco.draw(iterations)
  870. except KeyboardInterrupt:
  871. pass # just use what it has calculated so far, I guess
  872. for v in graph.C[0].sV:
  873. for n in tree.nodes:
  874. if n.name == v.data:
  875. n.location.x = v.view.xy[1]
  876. n.location.y = v.view.xy[0]
  877. n.select = True
  878. # now we can take all the input nodes and try to put them in a sensible place
  879. # not sure why but this absolutely does not do anything
  880. for n_name in no_links:
  881. n = tree.nodes.get(n_name)
  882. next_node = None
  883. for output in n.outputs:
  884. if output.is_linked == True:
  885. next_node = output.links[0].to_node
  886. break
  887. # let's see if the next node
  888. if next_node:
  889. # need to find the other node in the same layer...
  890. other_node = None
  891. for s_input in next_node.inputs:
  892. if s_input.is_linked:
  893. other_node = s_input.links[0].from_node
  894. if other_node is n:
  895. continue
  896. else:
  897. break
  898. if other_node:
  899. n.location = other_node.location
  900. n.location.y -= other_node.height*2
  901. else: # we'll just position it next to the next node
  902. n.location = next_node.location
  903. n.location.x -= next_node.width*1.5
  904. def project_point_to_plane(point, origin, normal):
  905. return point - normal.dot(point- origin)*normal
  906. ####################################
  907. # CURVE STUFF
  908. ####################################
  909. def make_perpendicular(v1, v2):
  910. from ..base_definitions import FLOAT_EPSILON
  911. if (v1.length_squared < FLOAT_EPSILON) or (v2.length_squared < FLOAT_EPSILON):
  912. raise RuntimeError("Cannot generate perpendicular vetor for zero-length vector")
  913. projected = (v2.dot(v1) / v1.dot(v1)) * v1
  914. perpendicular = v2 - projected
  915. return perpendicular
  916. # this stuff could be branchless but I don't use it much TODO
  917. def cap(val, maxValue):
  918. if (val > maxValue):
  919. return maxValue
  920. return val
  921. def capMin(val, minValue):
  922. if (val < minValue):
  923. return minValue
  924. return val
  925. def wrap(min : float, max : float, value: float) -> float:
  926. range = max-min; remainder = value % range
  927. if remainder > max: return min + remainder-max
  928. else: return remainder
  929. def lerpVal(a, b, fac = 0.5):
  930. return a + ( (b-a) * fac)
  931. #wtf this doesn't do anything even remotely similar to wrap
  932. # HACK BAD FIXME UNBREAK ME BAD
  933. # I don't understand what this function does but I am using it in multiple places?
  934. def old_bad_wrap_that_should_be_refactored(val, maxValue, minValue = None):
  935. if (val > maxValue):
  936. return (-1 * ((maxValue - val) + 1))
  937. if ((minValue) and (val < minValue)):
  938. return (val + maxValue)
  939. return val
  940. #TODO clean this up
  941. def extract_spline_suffix(spline_index):
  942. return ".spline."+str(spline_index).zfill(3)+".extracted"
  943. def do_extract_spline(data, spline):
  944. remove_me = []
  945. for other_spline in data.splines:
  946. if other_spline != spline: remove_me.append(other_spline)
  947. while remove_me: data.splines.remove(remove_me.pop())
  948. def extract_spline(curve, spline_index):
  949. """ Given a curve object and spline index, returns a new object
  950. containing only the selcted spline. The new object is bound to
  951. the original curve.
  952. """
  953. if len(curve.data.splines) == 1:
  954. return curve # nothing to do here.
  955. spline_suffix = extract_spline_suffix(spline_index)
  956. from bpy import data
  957. if (new_ob := data.objects.get(curve.name+spline_suffix)) is None:
  958. new_ob=curve.copy(); new_ob.name=curve.name+spline_suffix
  959. # if the data exists, it is probably stale, so delete it and start over.
  960. if (old_data := data.objects.get(curve.data.name+spline_suffix)) is not None:
  961. data.curves.remove(old_data)
  962. new_data=curve.data.copy(); new_data.name=curve.data.name+spline_suffix
  963. new_ob.data = new_data
  964. # do not check for index error here, it is the calling function's responsibility
  965. do_extract_spline(new_data, new_data.splines[spline_index])
  966. return new_ob
  967. def bind_extracted_spline_to_curve(new_ob, curve):
  968. # Set up a relationship between the new object and the old object
  969. # now, weirdly enough - we can't use parenting very easily because Blender
  970. # defines the parent on a curve relative to the evaluated path animation
  971. # Setting the inverse matrix is too much work. Use Copy Transforms instead.
  972. from ..xForm_nodes import reset_object_data
  973. reset_object_data(new_ob)
  974. c = new_ob.constraints.new("COPY_TRANSFORMS"); c.target=curve
  975. new_ob.parent=curve
  976. return new_ob
  977. def get_extracted_spline_object(proto_curve, spline_index, mContext):
  978. # we're storing it separately like this to ensure all nodes use the same
  979. # object if they extract the same spline for use by Mantis.
  980. # this should be transparent to the user since it is working around a
  981. # a limitation in Blender.
  982. extracted_spline_name = proto_curve.name+extract_spline_suffix(spline_index)
  983. if curve := mContext.b_objects.get(extracted_spline_name):
  984. return curve
  985. else:
  986. curve = extract_spline(proto_curve, spline_index)
  987. if curve.name != proto_curve.name: # if there is only one spline, no
  988. bind_extracted_spline_to_curve(curve, proto_curve)# dupe is created.
  989. mContext.b_objects[extracted_spline_name] = curve
  990. return curve
  991. def nurbs_copy_bez_spline(curve, bez_spline, do_setup=True):
  992. other_spline= curve.data.splines.new('NURBS')
  993. other_spline.use_endpoint_u=True
  994. other_spline.use_bezier_u=True
  995. bez_pts = bez_spline.bezier_points
  996. bez_data=[]
  997. for i, bez_pt in enumerate(bez_pts):
  998. if i > 0:
  999. bez_data.append(bez_pt.handle_left.copy())
  1000. bez_data.append(bez_pt.co.copy())
  1001. if i != len(bez_pts)-1:
  1002. bez_data.append(bez_pt.handle_right.copy())
  1003. other_spline.points.add(len(bez_data)-1)
  1004. for i, pt in enumerate(bez_data):
  1005. other_spline.points[i].co=(*pt,1.0) # add the W value here
  1006. if do_setup: # do the stuff that makes it behave the same as a bez spline
  1007. other_spline.use_endpoint_u = True; other_spline.use_bezier_u = True
  1008. other_spline.order_u=4 # set to 1 for poly
  1009. return other_spline
  1010. def RibbonMeshEdgeLengths(m, ribbon):
  1011. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  1012. lengths = []
  1013. for i in range( len( tE ) ): #tE and bE are same length
  1014. if (c == True):
  1015. v1NextInd = tE[old_bad_wrap_that_should_be_refactored((i+1), len(tE) - 1)]
  1016. else:
  1017. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  1018. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  1019. if (c == True):
  1020. v2NextInd = bE[old_bad_wrap_that_should_be_refactored((i+1), len(bE) - 1)]
  1021. else:
  1022. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  1023. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  1024. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  1025. # get the center, edges may not be straight so total length
  1026. # of one edge may be more than the ribbon center's length
  1027. lengths.append(( v - vNext ).length)
  1028. return lengths
  1029. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  1030. from ..base_definitions import FLOAT_EPSILON
  1031. crvRadius = 0
  1032. crv.data.offset = 0
  1033. if (crv.data.bevel_depth < FLOAT_EPSILON):
  1034. crvRadius = crv.data.extrude
  1035. else: #Set ribbon from bevel depth
  1036. crvRadius = crv.data.bevel_depth
  1037. crv.data.bevel_depth = 0
  1038. crv.data.extrude = crvRadius
  1039. if (crvRadius < FLOAT_EPSILON):
  1040. crv.data.extrude = defaultRadius
  1041. def SetRibbonData(m, ribbon):
  1042. #maybe this could be incorporated into the DetectWireEdges function?
  1043. #maybe I can check for closed poly curves here? under what other circumstance
  1044. # will I find the ends of the wire have identical coordinates?
  1045. ribbonData = []
  1046. tE = ribbon[0].copy(); bE = ribbon[1].copy()
  1047. lengths = RibbonMeshEdgeLengths(m, ribbon)
  1048. lengths.append(0)
  1049. totalLength = sum(lengths)
  1050. for i, (t, b) in enumerate(zip(tE, bE)):
  1051. ind = old_bad_wrap_that_should_be_refactored( (i + 1), len(tE) - 1 )
  1052. tNext = tE[ind]; bNext = bE[ind]
  1053. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  1054. #if this is a circle, the last v in vertData has a length, otherwise 0
  1055. return ribbonData, totalLength
  1056. def WireMeshEdgeLengths(m, wire):
  1057. circle = False
  1058. vIndex = wire.copy()
  1059. for e in m.edges:
  1060. if ((e.vertices[0] == vIndex[-1]) and (e.vertices[1] == vIndex[0])):
  1061. #this checks for an edge between the first and last vertex in the wire
  1062. circle = True
  1063. break
  1064. lengths = []
  1065. for i in range(len(vIndex)):
  1066. v = m.vertices[vIndex[i]]
  1067. if (circle == True):
  1068. vNextInd = vIndex[old_bad_wrap_that_should_be_refactored((i+1), len(vIndex) - 1)]
  1069. else:
  1070. vNextInd = vIndex[cap((i+1), len(vIndex) - 1 )]
  1071. vNext = m.vertices[vNextInd]
  1072. lengths.append(( v.co - vNext.co ).length)
  1073. #if this is a circular wire mesh, this should wrap instead of cap
  1074. return lengths
  1075. def GetDataFromWire(m, wire):
  1076. vertData = []
  1077. vIndex = wire.copy()
  1078. lengths = WireMeshEdgeLengths(m, wire)
  1079. lengths.append(0)
  1080. totalLength = sum(lengths)
  1081. for i, vInd in enumerate(vIndex):
  1082. #-1 to avoid IndexError
  1083. vNext = vIndex[ (old_bad_wrap_that_should_be_refactored(i+1, len(vIndex) - 1)) ]
  1084. vertData.append((vInd, vNext, lengths[i]))
  1085. #if this is a circle, the last v in vertData has a length, otherwise 0
  1086. return vertData, totalLength
  1087. def DetectWireEdges(mesh):
  1088. # Returns a list of vertex indices belonging to wire meshes
  1089. # NOTE: this assumes a mesh object with only wire meshes
  1090. ret = []
  1091. import bmesh
  1092. bm = bmesh.new()
  1093. try:
  1094. bm.from_mesh(mesh)
  1095. ends = []
  1096. for v in bm.verts:
  1097. if (len(v.link_edges) == 1):
  1098. ends.append(v.index)
  1099. for e in bm.edges:
  1100. assert (e.is_wire == True),"This function can only run on wire meshes"
  1101. if (e.verts[1].index - e.verts[0].index != 1):
  1102. ends.append(e.verts[1].index)
  1103. ends.append(e.verts[0].index)
  1104. for i in range(len(ends)//2): # // is floor division
  1105. beg = ends[i*2]
  1106. end = ends[(i*2)+1]
  1107. indices = [(j + beg) for j in range ((end - beg) + 1)]
  1108. ret.append(indices)
  1109. finally:
  1110. bm.free()
  1111. return ret
  1112. def FindNearestPointOnWireMesh(m, pointsList):
  1113. from mathutils import Vector
  1114. from mathutils.geometry import intersect_point_line
  1115. from math import sqrt
  1116. wires = DetectWireEdges(m)
  1117. ret = []
  1118. # prevFactor = None
  1119. for wire, points in zip(wires, pointsList):
  1120. vertData, total_length = GetDataFromWire(m, wire)
  1121. factorsOut = []
  1122. for p in points:
  1123. prevDist = float('inf')
  1124. curDist = float('inf')
  1125. v1 = None
  1126. v2 = None
  1127. for i in range(len(vertData) - 1):
  1128. #but it shouldn't check the last one
  1129. if (p == m.vertices[i].co):
  1130. v1 = vertData[i]
  1131. v2 = vertData[i+1]
  1132. offset = 0
  1133. break
  1134. else:
  1135. curDist = ( ((m.vertices[vertData[i][0]].co - p).length) +
  1136. ((m.vertices[vertData[i][1]].co - p).length) )/2
  1137. if (curDist < prevDist):
  1138. v1 = vertData[i]
  1139. v2 = vertData[i+1]
  1140. prevDist = curDist
  1141. offset = intersect_point_line(p, m.vertices[v1[0]].co,
  1142. m.vertices[v2[0]].co)[1]
  1143. if (offset < 0):
  1144. offset = 0
  1145. elif (offset > 1):
  1146. offset = 1
  1147. # Assume the vertices are in order
  1148. v1Length = 0
  1149. v2Length = v2[2]
  1150. for i in range(v1[0]):
  1151. v1Length += vertData[i][2]
  1152. factor = ((offset * (v2Length)) + v1Length )/total_length
  1153. factor = wrap(0, 1, factor) # doesn't hurt to wrap it if it's over 1 or less than 0
  1154. factorsOut.append(factor)
  1155. ret.append( factorsOut )
  1156. return ret
  1157. def mesh_from_curve(crv, context, ribbon=True):
  1158. """Utility function for converting a mesh to a curve
  1159. which will return the correct mesh even with modifiers"""
  1160. import bpy
  1161. m = None
  1162. crv_ob = crv.copy()
  1163. crv_data_copy = crv.data.copy()
  1164. crv_ob.data = crv_data_copy
  1165. if (len(crv_ob.modifiers) > 0):
  1166. do_unlink = False
  1167. if (not context.scene.collection.all_objects.get(crv_ob.name)):
  1168. context.collection.objects.link(crv_ob) # i guess this forces the dg to update it?
  1169. do_unlink = True
  1170. dg = context.view_layer.depsgraph
  1171. # just gonna modify it for now lol
  1172. if ribbon:
  1173. EnsureCurveIsRibbon(crv_ob)
  1174. else:
  1175. crv_ob.data.bevel_depth=0
  1176. crv_ob.data.extrude=0
  1177. crv_ob.data.offset=0
  1178. # try:
  1179. dg.update()
  1180. mOb = crv_ob.evaluated_get(dg)
  1181. m = bpy.data.meshes.new_from_object(mOb)
  1182. m.name=crv_ob.data.name+'_mesh'
  1183. if (do_unlink):
  1184. context.collection.objects.unlink(crv_ob)
  1185. else: # (ಥ﹏ಥ) why can't I just use this !
  1186. # for now I will just do it like this
  1187. if ribbon:
  1188. EnsureCurveIsRibbon(crv_ob)
  1189. else:
  1190. crv_ob.data.bevel_depth=0
  1191. crv_ob.data.extrude=0
  1192. crv_ob.data.offset=0
  1193. m = bpy.data.meshes.new_from_object(crv_ob)
  1194. bpy.data.objects.remove(crv_ob)
  1195. return m
  1196. def DetectRibbon(f, bm, skipMe):
  1197. fFirst = f.index
  1198. cont = True
  1199. circle = False
  1200. tEdge, bEdge = [],[]
  1201. while (cont == True):
  1202. skipMe.add(f.index)
  1203. tEdge.append (f.loops[0].vert.index) # top-left
  1204. bEdge.append (f.loops[3].vert.index) # bottom-left
  1205. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  1206. nFaces = nEdge.link_faces
  1207. if (len(nFaces) == 1):
  1208. cont = False
  1209. else:
  1210. for nFace in nFaces:
  1211. if (nFace != f):
  1212. f = nFace
  1213. break
  1214. if (f.index == fFirst):
  1215. cont = False
  1216. circle = True
  1217. if (cont == False): # we've reached the end, get the last two:
  1218. tEdge.append (f.loops[1].vert.index) # top-right
  1219. bEdge.append (f.loops[2].vert.index) # bottom-right
  1220. # this will create a loop for rings --
  1221. # "the first shall be the last and the last shall be first"
  1222. return (tEdge,bEdge,circle)
  1223. def DetectRibbons(m, fReport = None):
  1224. # Returns list of vertex indices belonging to ribbon mesh edges
  1225. # NOTE: this assumes a mesh object with only ribbon meshes
  1226. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  1227. import bmesh
  1228. bm = bmesh.new()
  1229. bm.from_mesh(m)
  1230. mIslands, mIsland = [], []
  1231. skipMe = set()
  1232. bm.faces.ensure_lookup_table()
  1233. #first, get a list of mesh islands
  1234. for f in bm.faces:
  1235. if (f.index in skipMe):
  1236. continue #already done here
  1237. checkMe = [f]
  1238. while (len(checkMe) > 0):
  1239. facesFound = 0
  1240. for f in checkMe:
  1241. if (f.index in skipMe):
  1242. continue #already done here
  1243. mIsland.append(f)
  1244. skipMe.add(f.index)
  1245. for e in f.edges:
  1246. checkMe += e.link_faces
  1247. if (facesFound == 0):
  1248. #this is the last iteration
  1249. mIslands.append(mIsland)
  1250. checkMe, mIsland = [], []
  1251. ribbons = []
  1252. skipMe = set() # to store ends already checked
  1253. for mIsl in mIslands:
  1254. ribbon = None
  1255. first = float('inf')
  1256. for f in mIsl:
  1257. if (f.index in skipMe):
  1258. continue #already done here
  1259. if (f.index < first):
  1260. first = f.index
  1261. adjF = 0
  1262. for e in f.edges:
  1263. adjF+= (len(e.link_faces) - 1)
  1264. # every face other than this one is added to the list
  1265. if (adjF == 1):
  1266. ribbon = (DetectRibbon(f, bm, skipMe) )
  1267. break
  1268. if (ribbon == None):
  1269. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  1270. ribbons.append(ribbon)
  1271. # print (ribbons)
  1272. return ribbons
  1273. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  1274. #Note, factors list should be equal in length the the number of wires
  1275. #Now working for multiple wires, ugly tho
  1276. if (ribbons == None):
  1277. ribbons = DetectRibbons(m, fReport=fReport)
  1278. if (ribbons is None):
  1279. if (fReport):
  1280. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  1281. else:
  1282. print ("No ribbon to get data from.")
  1283. return None
  1284. ret = []
  1285. for factors, ribbon in zip(factorsList, ribbons):
  1286. points = []
  1287. widths = []
  1288. normals = []
  1289. ribbonData, totalLength = SetRibbonData(m, ribbon)
  1290. for fac in factors:
  1291. if (fac == 0):
  1292. data = ribbonData[0]
  1293. curFac = 0
  1294. elif (fac == 1):
  1295. data = ribbonData[-1]
  1296. curFac = 0
  1297. else:
  1298. targetLength = totalLength * fac
  1299. data = ribbonData[0]
  1300. curLength = 0
  1301. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  1302. if (curLength >= targetLength):
  1303. break
  1304. curLength += length
  1305. data = ( (t, b), (tNext, bNext), length,)
  1306. targetLengthAtEdge = (curLength - targetLength)
  1307. if (targetLength == 0):
  1308. curFac = 0
  1309. elif (targetLength == totalLength):
  1310. curFac = 1
  1311. else:
  1312. # NOTE: This can be Zero. Find out why!
  1313. if data[2] == 0:
  1314. curFac=0
  1315. else:
  1316. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  1317. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  1318. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  1319. #location
  1320. loc1 = (t1.co).lerp(b1.co, 0.5)
  1321. loc2 = (t2.co).lerp(b2.co, 0.5)
  1322. #width
  1323. w1 = (t1.co - b1.co).length/2
  1324. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  1325. #normal
  1326. n1 = (t1.normal).slerp(b1.normal, 0.5)
  1327. n2 = (t1.normal).slerp(b2.normal, 0.5)
  1328. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  1329. curFac = 0
  1330. #don't interpolate if at the end of a ribbon that isn't circular
  1331. if ( 0 < curFac < 1):
  1332. outPoint = loc1.lerp(loc2, curFac)
  1333. outNorm = n1.lerp(n2, curFac)
  1334. outWidth = w1 + ( (w2-w1) * curFac)
  1335. elif (curFac <= 0):
  1336. outPoint = loc1.copy()
  1337. outNorm = n1
  1338. outWidth = w1
  1339. elif (curFac >= 1):
  1340. outPoint = loc2.copy()
  1341. outNorm = n2
  1342. outWidth = w2
  1343. outPoint = mat @ outPoint
  1344. outNorm.normalize()
  1345. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  1346. widths.append ( outWidth )
  1347. normals.append( outNorm )
  1348. ret.append( (points, widths, normals) )
  1349. return ret # this is a list of tuples containing three lists
  1350. from mathutils import Vector
  1351. # Used for filling the Curve LUTimport numpy as np
  1352. import numpy as np
  1353. def all_data_from_ribbon(mesh, mat, ribbon):
  1354. top_indices, bottom_indices, is_closed = ribbon
  1355. top_indices = np.asarray(top_indices, dtype=np.intp)
  1356. bottom_indices = np.asarray(bottom_indices, dtype=np.intp)
  1357. count = len(top_indices)
  1358. assert count >= 2, "this should never happen, report this as a bug"
  1359. # we'll use numpy to calculate the positions and normals because it is fast.
  1360. vertex_count = len(mesh.vertices)
  1361. coordinates = np.empty(vertex_count * 3, dtype=np.float64)
  1362. mesh.vertices.foreach_get("co", coordinates)
  1363. coordinates = coordinates.reshape((-1, 3))
  1364. vertex_normals = np.empty(vertex_count * 3, dtype=np.float64)
  1365. mesh.vertices.foreach_get("normal", vertex_normals)
  1366. vertex_normals = vertex_normals.reshape((-1, 3))
  1367. top_local = coordinates[top_indices]; bottom_local = coordinates[bottom_indices]
  1368. # similarly we have to make the world matrix a numpy array
  1369. transform = np.asarray(mat, dtype=np.float64)
  1370. basis = transform[:3, :3]; translation = transform[:3, 3]
  1371. #.T is transpose because this numpy array expects row-major
  1372. top_positions = top_local @ basis.T + translation
  1373. bottom_positions = bottom_local @ basis.T + translation
  1374. positions = (top_positions + bottom_positions) * 0.5
  1375. radii = np.linalg.norm(top_positions - bottom_positions, axis=1) * 0.5
  1376. # transform the potisions by the object's matrix, mat
  1377. # and the normals need a slightly different transformation
  1378. normal_transform = np.linalg.inv(basis).T
  1379. local_normals = ( vertex_normals[top_indices] + vertex_normals[bottom_indices] )
  1380. normals = local_normals @ normal_transform.T
  1381. normal_lengths = np.linalg.norm(normals, axis=1)
  1382. # Normalize the normals by dividing them by the lengths. avoid dividing by 0
  1383. normals = np.divide(
  1384. normals,
  1385. normal_lengths[:, None],
  1386. out=np.zeros_like(normals),
  1387. where=normal_lengths[:, None] != 0,
  1388. )
  1389. # all of this incoming/outgoing subtraction stuff is doing the following:
  1390. # take the current vertex positon and get the tangent vector of each segment
  1391. # it is a part of, then average them
  1392. if is_closed: # have to adjust it back, I don't really know if this works
  1393. incoming = positions - np.roll(positions, 1, axis=0)
  1394. outgoing = np.roll(positions, -1, axis=0) - positions
  1395. else:
  1396. incoming = np.zeros_like(positions); outgoing = np.zeros_like(positions)
  1397. incoming[1:] = positions[1:] - positions[:-1]
  1398. outgoing[:-1] = positions[1:] - positions[:-1]
  1399. incoming[0] = outgoing[0]
  1400. outgoing[-1] = incoming[-1]
  1401. incoming_lengths = np.linalg.norm(incoming, axis=1)
  1402. outgoing_lengths = np.linalg.norm(outgoing, axis=1)
  1403. # the segments may be different lengths so we have to normalize them
  1404. incoming = np.divide(
  1405. incoming,
  1406. incoming_lengths[:, None],
  1407. out=np.zeros_like(incoming),
  1408. where=incoming_lengths[:, None] != 0,
  1409. )
  1410. outgoing = np.divide(
  1411. outgoing,
  1412. outgoing_lengths[:, None],
  1413. out=np.zeros_like(outgoing),
  1414. where=outgoing_lengths[:, None] != 0,
  1415. )
  1416. # then we add them together and normalize again to average them
  1417. tangents = incoming + outgoing
  1418. tangent_lengths = np.linalg.norm(tangents, axis=1)
  1419. tangents = np.divide(
  1420. tangents,
  1421. tangent_lengths[:, None],
  1422. out=np.zeros_like(tangents),
  1423. where=tangent_lengths[:, None] != 0,
  1424. )
  1425. # calcualte the U value of the samples based on the length of the spline
  1426. segment_lengths = np.linalg.norm(positions[1:] - positions[:-1], axis=1)
  1427. if is_closed:
  1428. closing_length = np.linalg.norm(positions[0] - positions[-1])
  1429. total_length = segment_lengths.sum() + closing_length
  1430. else:
  1431. total_length = segment_lengths.sum()
  1432. if total_length:
  1433. u_samples = np.concatenate(([0.0], np.cumsum(segment_lengths))) / total_length
  1434. else:
  1435. u_samples = np.zeros(count, dtype=np.float64)
  1436. # now we have to convert the values back to values Blender uses
  1437. # TODO eventually I want to port everything to numpy even tho it is ugly
  1438. u_samples = tuple(u_samples)
  1439. radii = tuple(radii)
  1440. from mathutils import Vector
  1441. positions = [Vector(elem) for elem in positions]
  1442. normals = [Vector(elem) for elem in normals]
  1443. tangents = [Vector(elem) for elem in tangents]
  1444. return u_samples, positions, normals, tangents, radii
  1445. #This bisection search is generic, and it searches based on the
  1446. # magnitude of the error, rather than the sign.
  1447. # If the sign of the error is meaningful, a simpler function
  1448. # can be used.
  1449. def do_bisect_search_by_magnitude(
  1450. owner,
  1451. attribute,
  1452. index = None,
  1453. test_function = None,
  1454. modify = None,
  1455. max_iterations = 10000,
  1456. threshold = 0.0001,
  1457. thresh2 = 0.0005,
  1458. context = None,
  1459. update_dg = None,
  1460. ):
  1461. from math import floor
  1462. i = 0; best_so_far = 0; best = float('inf')
  1463. min = 0; center = max_iterations//2; max = max_iterations
  1464. # enforce getting the absolute value, in case the function has sign information
  1465. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  1466. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  1467. while (i <= max_iterations):
  1468. upper = (max - ((max-center))//2)
  1469. modify(owner, attribute, index, upper, context = context); error1 = test()
  1470. lower = (center - ((center-min))//2)
  1471. modify(owner, attribute, index, lower, context = context); error2 = test()
  1472. if (error1 < error2):
  1473. min = center
  1474. center, check = upper, upper
  1475. error = error1
  1476. else:
  1477. max = center
  1478. center, check = lower, lower
  1479. error = error2
  1480. if (error <= threshold) or (min == max-1):
  1481. break
  1482. if (error < thresh2):
  1483. j = min
  1484. while (j < max):
  1485. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  1486. error = test()
  1487. if (error < best):
  1488. best_so_far = j; best = error
  1489. if (error <= threshold):
  1490. break
  1491. j+=1
  1492. else: # loop has completed without finding a solution
  1493. i = best_so_far; error = test()
  1494. modify(owner, attribute, index, best_so_far, context = context)
  1495. break
  1496. if (error < best):
  1497. best_so_far = check; best = error
  1498. i+=1
  1499. if update_dg:
  1500. update_dg.update()
  1501. else: # Loop has completed without finding a solution
  1502. i = best_so_far
  1503. modify(owner, attribute, best_so_far, context = context); i+=1