utilities.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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 .base_definitions 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. # This is really, really stupid way to do this
  537. def gen_nc_input_for_data(socket):
  538. # Class List #TODO deduplicate
  539. from . import xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers
  540. from .internal_containers import NoOpNode
  541. classes = {}
  542. for module in [xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers]:
  543. for cls in module.TellClasses():
  544. classes[cls.__name__] = cls
  545. #
  546. socket_class_map = {
  547. "MatrixSocket" : classes["InputMatrix"],
  548. "xFormSocket" : None,
  549. "RelationshipSocket" : NoOpNode,
  550. "DeformerSocket" : NoOpNode,
  551. "GeometrySocket" : classes["InputExistingGeometryData"],
  552. "EnableSocket" : classes["InputBoolean"],
  553. "HideSocket" : classes["InputBoolean"],
  554. #
  555. "DriverSocket" : None,
  556. "DriverVariableSocket" : None,
  557. "FCurveSocket" : None,
  558. "KeyframeSocket" : None,
  559. "BoneCollectionSocket" : classes["InputString"],
  560. #
  561. "xFormParameterSocket" : None,
  562. "ParameterBoolSocket" : classes["InputBoolean"],
  563. "ParameterIntSocket" : classes["InputFloat"], #TODO: make an Int node for this
  564. "ParameterFloatSocket" : classes["InputFloat"],
  565. "ParameterVectorSocket" : classes["InputVector"],
  566. "ParameterStringSocket" : classes["InputString"],
  567. #
  568. "TransformSpaceSocket" : classes["InputTransformSpace"],
  569. "BooleanSocket" : classes["InputBoolean"],
  570. "BooleanThreeTupleSocket" : classes["InputBooleanThreeTuple"],
  571. "RotationOrderSocket" : classes["InputRotationOrder"],
  572. "QuaternionSocket" : None,
  573. "QuaternionSocketAA" : None,
  574. "IntSocket" : classes["InputFloat"],
  575. "StringSocket" : classes["InputString"],
  576. #
  577. "BoolUpdateParentNode" : classes["InputBoolean"],
  578. "IKChainLengthSocket" : classes["InputFloat"],
  579. "EnumInheritScale" : classes["InputString"],
  580. "EnumRotationMix" : classes["InputString"],
  581. "EnumRotationMixCopyTransforms" : classes["InputString"],
  582. "EnumMaintainVolumeStretchTo" : classes["InputString"],
  583. "EnumRotationStretchTo" : classes["InputString"],
  584. "EnumTrackAxis" : classes["InputString"],
  585. "EnumUpAxis" : classes["InputString"],
  586. "EnumLockAxis" : classes["InputString"],
  587. "EnumLimitMode" : classes["InputString"],
  588. "EnumYScaleMode" : classes["InputString"],
  589. "EnumXZScaleMode" : classes["InputString"],
  590. "EnumCurveSocket" : classes["InputString"],
  591. "EnumMetaRigSocket" : classes["InputString"],
  592. # Deformers
  593. "EnumSkinning" : classes["InputString"],
  594. #
  595. "FloatSocket" : classes["InputFloat"],
  596. "FloatFactorSocket" : classes["InputFloat"],
  597. "FloatPositiveSocket" : classes["InputFloat"],
  598. "FloatAngleSocket" : classes["InputFloat"],
  599. "VectorSocket" : classes["InputVector"],
  600. "VectorEulerSocket" : classes["InputVector"],
  601. "VectorTranslationSocket" : classes["InputVector"],
  602. "VectorScaleSocket" : classes["InputVector"],
  603. # Drivers
  604. "EnumDriverVariableType" : classes["InputString"],
  605. "EnumDriverVariableEvaluationSpace" : classes["InputString"],
  606. "EnumDriverRotationMode" : classes["InputString"],
  607. "EnumDriverType" : classes["InputString"],
  608. "EnumKeyframeInterpTypeSocket" : classes["InputString"],
  609. "EnumKeyframeBezierHandleTypeSocket" : classes["InputString"],
  610. # Math
  611. "MathFloatOperation" : classes["InputString"],
  612. "MathVectorOperation" : classes["InputString"],
  613. "MatrixTransformOperation" : classes["InputString"],
  614. # Schema
  615. "WildcardSocket" : None,
  616. }
  617. return socket_class_map.get(socket.bl_idname, None)
  618. ####################################
  619. # CURVE STUFF
  620. ####################################
  621. def rotate(l, n):
  622. if ( not ( isinstance(n, int) ) ): #print an error if n is not an int:
  623. raise TypeError("List slice must be an int, not float.")
  624. return l[n:] + l[:n]
  625. #from stack exchange, thanks YXD
  626. # this stuff could be branchless but I don't use it much TODO
  627. def cap(val, maxValue):
  628. if (val > maxValue):
  629. return maxValue
  630. return val
  631. def capMin(val, minValue):
  632. if (val < minValue):
  633. return minValue
  634. return val
  635. # def wrap(val, min=0, max=1):
  636. # raise NotImplementedError
  637. #wtf this doesn't do anything even remotely similar to wrap, or useful in
  638. # HACK BAD FIXME UNBREAK ME BAD
  639. # I don't understand what this function does but I am using it in multiple places?
  640. def wrap(val, maxValue, minValue = None):
  641. if (val > maxValue):
  642. return (-1 * ((maxValue - val) + 1))
  643. if ((minValue) and (val < minValue)):
  644. return (val + maxValue)
  645. return val
  646. #TODO clean this up
  647. def layerMaskCompare(mask_a, mask_b):
  648. compare = 0
  649. for a, b in zip(mask_a, mask_b):
  650. if (a != b):
  651. compare+=1
  652. if (compare == 0):
  653. return True
  654. return False
  655. def lerpVal(a, b, fac = 0.5):
  656. return a + ( (b-a) * fac)
  657. def RibbonMeshEdgeLengths(m, ribbon):
  658. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  659. lengths = []
  660. for i in range( len( tE ) ): #tE and bE are same length
  661. if (c == True):
  662. v1NextInd = tE[wrap((i+1), len(tE) - 1)]
  663. else:
  664. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  665. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  666. if (c == True):
  667. v2NextInd = bE[wrap((i+1), len(bE) - 1)]
  668. else:
  669. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  670. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  671. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  672. # get the center, edges may not be straight so total length
  673. # of one edge may be more than the ribbon center's length
  674. lengths.append(( v - vNext ).length)
  675. return lengths
  676. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  677. crvRadius = 0
  678. if (crv.data.bevel_depth == 0):
  679. crvRadius = crv.data.extrude
  680. else: #Set ribbon from bevel depth
  681. crvRadius = crv.data.bevel_depth
  682. crv.data.bevel_depth = 0
  683. crv.data.extrude = crvRadius
  684. if (crvRadius == 0):
  685. crv.data.extrude = defaultRadius
  686. def SetRibbonData(m, ribbon):
  687. #maybe this could be incorporated into the DetectWireEdges function?
  688. #maybe I can check for closed poly curves here? under what other circumstance
  689. # will I find the ends of the wire have identical coordinates?
  690. ribbonData = []
  691. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  692. #
  693. lengths = RibbonMeshEdgeLengths(m, ribbon)
  694. lengths.append(0)
  695. totalLength = sum(lengths)
  696. # m.calc_normals() #calculate normals
  697. # it appears this has been removed.
  698. for i, (t, b) in enumerate(zip(tE, bE)):
  699. ind = wrap( (i + 1), len(tE) - 1 )
  700. tNext = tE[ind]; bNext = bE[ind]
  701. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  702. #if this is a circle, the last v in vertData has a length, otherwise 0
  703. return ribbonData, totalLength
  704. def mesh_from_curve(crv, context,):
  705. """Utility function for converting a mesh to a curve
  706. which will return the correct mesh even with modifiers"""
  707. import bpy
  708. if (len(crv.modifiers) > 0):
  709. do_unlink = False
  710. if (not context.scene.collection.all_objects.get(crv.name)):
  711. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  712. do_unlink = True
  713. dg = context.view_layer.depsgraph
  714. # just gonna modify it for now lol
  715. EnsureCurveIsRibbon(crv)
  716. # try:
  717. dg.update()
  718. mOb = crv.evaluated_get(dg)
  719. m = bpy.data.meshes.new_from_object(mOb)
  720. m.name=crv.data.name+'_mesh'
  721. if (do_unlink):
  722. context.collection.objects.unlink(crv)
  723. return m
  724. # except: #dg is None?? # FIX THIS BUG BUG BUG
  725. # print ("Warning: could not apply modifiers on curve")
  726. # return bpy.data.meshes.new_from_object(crv)
  727. else: # (ಥ﹏ಥ) why can't I just use this !
  728. # for now I will just do it like this
  729. EnsureCurveIsRibbon(crv)
  730. return bpy.data.meshes.new_from_object(crv)
  731. def DetectRibbon(f, bm, skipMe):
  732. fFirst = f.index
  733. cont = True
  734. circle = False
  735. tEdge, bEdge = [],[]
  736. while (cont == True):
  737. skipMe.add(f.index)
  738. tEdge.append (f.loops[0].vert.index) # top-left
  739. bEdge.append (f.loops[3].vert.index) # bottom-left
  740. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  741. nFaces = nEdge.link_faces
  742. if (len(nFaces) == 1):
  743. cont = False
  744. else:
  745. for nFace in nFaces:
  746. if (nFace != f):
  747. f = nFace
  748. break
  749. if (f.index == fFirst):
  750. cont = False
  751. circle = True
  752. if (cont == False): # we've reached the end, get the last two:
  753. tEdge.append (f.loops[1].vert.index) # top-right
  754. bEdge.append (f.loops[2].vert.index) # bottom-right
  755. # this will create a loop for rings --
  756. # "the first shall be the last and the last shall be first"
  757. return (tEdge,bEdge,circle)
  758. def DetectRibbons(m, fReport = None):
  759. # Returns list of vertex indices belonging to ribbon mesh edges
  760. # NOTE: this assumes a mesh object with only ribbon meshes
  761. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  762. import bmesh
  763. bm = bmesh.new()
  764. bm.from_mesh(m)
  765. mIslands, mIsland = [], []
  766. skipMe = set()
  767. bm.faces.ensure_lookup_table()
  768. #first, get a list of mesh islands
  769. for f in bm.faces:
  770. if (f.index in skipMe):
  771. continue #already done here
  772. checkMe = [f]
  773. while (len(checkMe) > 0):
  774. facesFound = 0
  775. for f in checkMe:
  776. if (f.index in skipMe):
  777. continue #already done here
  778. mIsland.append(f)
  779. skipMe.add(f.index)
  780. for e in f.edges:
  781. checkMe += e.link_faces
  782. if (facesFound == 0):
  783. #this is the last iteration
  784. mIslands.append(mIsland)
  785. checkMe, mIsland = [], []
  786. ribbons = []
  787. skipMe = set() # to store ends already checked
  788. for mIsl in mIslands:
  789. ribbon = None
  790. first = float('inf')
  791. for f in mIsl:
  792. if (f.index in skipMe):
  793. continue #already done here
  794. if (f.index < first):
  795. first = f.index
  796. adjF = 0
  797. for e in f.edges:
  798. adjF+= (len(e.link_faces) - 1)
  799. # every face other than this one is added to the list
  800. if (adjF == 1):
  801. ribbon = (DetectRibbon(f, bm, skipMe) )
  802. break
  803. if (ribbon == None):
  804. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  805. ribbons.append(ribbon)
  806. # print (ribbons)
  807. return ribbons
  808. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  809. #Note, factors list should be equal in length the the number of wires
  810. #Now working for multiple wires, ugly tho
  811. if (ribbons == None):
  812. ribbons = DetectRibbons(m, fReport=fReport)
  813. if (ribbons is None):
  814. if (fReport):
  815. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  816. else:
  817. print ("No ribbon to get data from.")
  818. return None
  819. ret = []
  820. for factors, ribbon in zip(factorsList, ribbons):
  821. points = []
  822. widths = []
  823. normals = []
  824. ribbonData, totalLength = SetRibbonData(m, ribbon)
  825. for fac in factors:
  826. if (fac == 0):
  827. data = ribbonData[0]
  828. curFac = 0
  829. elif (fac == 1):
  830. data = ribbonData[-1]
  831. curFac = 0
  832. else:
  833. targetLength = totalLength * fac
  834. data = ribbonData[0]
  835. curLength = 0
  836. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  837. if (curLength >= targetLength):
  838. break
  839. curLength += length
  840. data = ( (t, b), (tNext, bNext), length,)
  841. targetLengthAtEdge = (curLength - targetLength)
  842. if (targetLength == 0):
  843. curFac = 0
  844. elif (targetLength == totalLength):
  845. curFac = 1
  846. else:
  847. try:
  848. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  849. except ZeroDivisionError:
  850. curFac = 0
  851. if (fReport):
  852. fReport(type = {'WARNING'}, message="Division by Zero.")
  853. else:
  854. prRed ("Division by Zero Error in evaluating data from curve.")
  855. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  856. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  857. #location
  858. loc1 = (t1.co).lerp(b1.co, 0.5)
  859. loc2 = (t2.co).lerp(b2.co, 0.5)
  860. #width
  861. w1 = (t1.co - b1.co).length/2
  862. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  863. #normal
  864. n1 = (t1.normal).slerp(b1.normal, 0.5)
  865. n2 = (t1.normal).slerp(b2.normal, 0.5)
  866. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  867. curFac = 0
  868. #don't interpolate if at the end of a ribbon that isn't circular
  869. if ( 0 < curFac < 1):
  870. outPoint = loc1.lerp(loc2, curFac)
  871. outNorm = n1.lerp(n2, curFac)
  872. outWidth = w1 + ( (w2-w1) * curFac)
  873. elif (curFac <= 0):
  874. outPoint = loc1.copy()
  875. outNorm = n1
  876. outWidth = w1
  877. elif (curFac >= 1):
  878. outPoint = loc2.copy()
  879. outNorm = n2
  880. outWidth = w2
  881. outPoint = mat @ outPoint
  882. outNorm.normalize()
  883. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  884. widths.append ( outWidth )
  885. normals.append( outNorm )
  886. ret.append( (points, widths, normals) )
  887. return ret # this is a list of tuples containing three lists
  888. #This bisection search is generic, and it searches based on the
  889. # magnitude of the error, rather than the sign.
  890. # If the sign of the error is meaningful, a simpler function
  891. # can be used.
  892. def do_bisect_search_by_magnitude(
  893. owner,
  894. attribute,
  895. index = None,
  896. test_function = None,
  897. modify = None,
  898. max_iterations = 10000,
  899. threshold = 0.0001,
  900. thresh2 = 0.0005,
  901. context = None,
  902. update_dg = None,
  903. ):
  904. from math import floor
  905. i = 0; best_so_far = 0; best = float('inf')
  906. min = 0; center = max_iterations//2; max = max_iterations
  907. # enforce getting the absolute value, in case the function has sign information
  908. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  909. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  910. while (i <= max_iterations):
  911. upper = (max - ((max-center))//2)
  912. modify(owner, attribute, index, upper, context = context); error1 = test()
  913. lower = (center - ((center-min))//2)
  914. modify(owner, attribute, index, lower, context = context); error2 = test()
  915. if (error1 < error2):
  916. min = center
  917. center, check = upper, upper
  918. error = error1
  919. else:
  920. max = center
  921. center, check = lower, lower
  922. error = error2
  923. if (error <= threshold) or (min == max-1):
  924. break
  925. if (error < thresh2):
  926. j = min
  927. while (j < max):
  928. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  929. error = test()
  930. if (error < best):
  931. best_so_far = j; best = error
  932. if (error <= threshold):
  933. break
  934. j+=1
  935. else: # loop has completed without finding a solution
  936. i = best_so_far; error = test()
  937. modify(owner, attribute, index, best_so_far, context = context)
  938. break
  939. if (error < best):
  940. best_so_far = check; best = error
  941. i+=1
  942. if update_dg:
  943. update_dg.update()
  944. else: # Loop has completed without finding a solution
  945. i = best_so_far
  946. modify(owner, attribute, best_so_far, context = context); i+=1