utilities.py 46 KB

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