utilities.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  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, node_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 = node_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 = node_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. can_descend = True
  386. check_nodes = [nc]
  387. while (len(check_nodes) > 0):
  388. node = check_nodes.pop()
  389. connected_nodes = node.hierarchy_dependencies.copy()
  390. for new_node in connected_nodes:
  391. if new_node in nodes: raise GraphError()
  392. nodes.append(new_node)
  393. return nodes
  394. ##################################################################################################
  395. # misc
  396. ##################################################################################################
  397. # this function is used a lot, so it is a good target for optimization.
  398. def to_mathutils_value(socket):
  399. if hasattr(socket, "default_value"):
  400. from mathutils import Matrix, Euler, Quaternion, Vector
  401. val = socket.default_value
  402. if socket.bl_idname in ['MatrixSocket']:
  403. return socket.TellValue()
  404. else:
  405. return val
  406. else:
  407. return None
  408. def all_trees_in_tree(base_tree, selected=False):
  409. """ Recursively finds all trees referenced in a given base-tree."""
  410. # note that this is recursive but not by tail-end recursion
  411. # a while-loop is a better way to do recursion in Python.
  412. trees = [base_tree]
  413. can_descend = True
  414. check_trees = [base_tree]
  415. while (len(check_trees) > 0): # this seems innefficient, why 2 loops?
  416. new_trees = []
  417. while (len(check_trees) > 0):
  418. tree = check_trees.pop()
  419. for node in tree.nodes:
  420. if selected == True and node.select == False:
  421. continue
  422. if new_tree := getattr(node, "node_tree", None):
  423. if new_tree in trees: continue
  424. new_trees.append(new_tree)
  425. trees.append(new_tree)
  426. check_trees = new_trees
  427. return trees
  428. # this is a destructive operation, not a pure function or whatever. That isn't good but I don't care.
  429. def SugiyamaGraph(tree, iterations):
  430. from grandalf.graphs import Vertex, Edge, Graph, graph_core
  431. class defaultview(object):
  432. w,h = 1,1
  433. xz = (0,0)
  434. no_links = set()
  435. verts = {}
  436. for n in tree.nodes:
  437. has_links=False
  438. for inp in n.inputs:
  439. if inp.is_linked:
  440. has_links=True
  441. break
  442. else:
  443. no_links.add(n.name)
  444. for out in n.outputs:
  445. if out.is_linked:
  446. has_links=True
  447. break
  448. else:
  449. try:
  450. no_links.remove(n.name)
  451. except KeyError:
  452. pass
  453. if not has_links:
  454. continue
  455. v = Vertex(n.name)
  456. v.view = defaultview()
  457. v.view.xy = n.location
  458. v.view.h = n.height*2.5
  459. v.view.w = n.width*2.2
  460. verts[n.name] = v
  461. edges = []
  462. for link in tree.links:
  463. weight = 1 # maybe this is useful
  464. edges.append(Edge(verts[link.from_node.name], verts[link.to_node.name], weight) )
  465. graph = Graph(verts.values(), edges)
  466. from grandalf.layouts import SugiyamaLayout
  467. sug = SugiyamaLayout(graph.C[0]) # no idea what .C[0] is
  468. roots=[]
  469. for node in tree.nodes:
  470. has_links=False
  471. for inp in node.inputs:
  472. if inp.is_linked:
  473. has_links=True
  474. break
  475. for out in node.outputs:
  476. if out.is_linked:
  477. has_links=True
  478. break
  479. if not has_links:
  480. continue
  481. if len(node.inputs)==0:
  482. roots.append(verts[node.name])
  483. else:
  484. for inp in node.inputs:
  485. if inp.is_linked==True:
  486. break
  487. else:
  488. roots.append(verts[node.name])
  489. sug.init_all(roots=roots,)
  490. sug.draw(iterations)
  491. for v in graph.C[0].sV:
  492. for n in tree.nodes:
  493. if n.name == v.data:
  494. n.location.x = v.view.xy[1]
  495. n.location.y = v.view.xy[0]
  496. # now we can take all the input nodes and try to put them in a sensible place
  497. for n_name in no_links:
  498. n = tree.nodes.get(n_name)
  499. next_n = None
  500. next_node = None
  501. for output in n.outputs:
  502. if output.is_linked == True:
  503. next_node = output.links[0].to_node
  504. break
  505. # let's see if the next node
  506. if next_node:
  507. # need to find the other node in the same layer...
  508. other_node = None
  509. for s_input in next_node.inputs:
  510. if s_input.is_linked:
  511. other_node = s_input.links[0].from_node
  512. if other_node is n:
  513. continue
  514. else:
  515. break
  516. if other_node:
  517. n.location = other_node.location
  518. n.location.y -= other_node.height*2
  519. else: # we'll just position it next to the next node
  520. n.location = next_node.location
  521. n.location.x -= next_node.width*1.5
  522. def project_point_to_plane(point, origin, normal):
  523. return point - normal.dot(point- origin)*normal
  524. ##################################################################################################
  525. # stuff I should probably refactor!!
  526. ##################################################################################################
  527. # what in the cuss is this horrible abomination??
  528. def class_for_mantis_prototype_node(prototype_node):
  529. """ This is a class which returns a class to instantiate for
  530. the given prototype node."""
  531. #from .node_container_classes import TellClasses
  532. from . import xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers
  533. classes = {}
  534. for module in [xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers]:
  535. for cls in module.TellClasses():
  536. classes[cls.__name__] = cls
  537. # I could probably do a string.replace() here
  538. # But I actually think this is a bad idea since I might not
  539. # want to use this name convention in the future
  540. # this is easy enough for now, may refactor.
  541. if prototype_node.bl_idname == 'xFormArmatureNode':
  542. return classes["xFormArmature"]
  543. elif prototype_node.bl_idname == 'xFormBoneNode':
  544. return classes["xFormBone"]
  545. elif prototype_node.bl_idname == 'xFormGeometryObject':
  546. return classes["xFormGeometryObject"]
  547. elif prototype_node.bl_idname == 'linkInherit':
  548. return classes["LinkInherit"]
  549. elif prototype_node.bl_idname == 'InputFloatNode':
  550. return classes["InputFloat"]
  551. elif prototype_node.bl_idname == 'InputVectorNode':
  552. return classes["InputVector"]
  553. elif prototype_node.bl_idname == 'InputBooleanNode':
  554. return classes["InputBoolean"]
  555. elif prototype_node.bl_idname == 'InputBooleanThreeTupleNode':
  556. return classes["InputBooleanThreeTuple"]
  557. elif prototype_node.bl_idname == 'InputRotationOrderNode':
  558. return classes["InputRotationOrder"]
  559. elif prototype_node.bl_idname == 'InputTransformSpaceNode':
  560. return classes["InputTransformSpace"]
  561. elif prototype_node.bl_idname == 'InputStringNode':
  562. return classes["InputString"]
  563. elif prototype_node.bl_idname == 'InputQuaternionNode':
  564. return classes["InputQuaternion"]
  565. elif prototype_node.bl_idname == 'InputQuaternionNodeAA':
  566. return classes["InputQuaternionAA"]
  567. elif prototype_node.bl_idname == 'InputMatrixNode':
  568. return classes["InputMatrix"]
  569. elif prototype_node.bl_idname == 'MetaRigMatrixNode':
  570. return classes["InputMatrix"]
  571. elif prototype_node.bl_idname == 'InputLayerMaskNode':
  572. return classes["InputLayerMask"]
  573. elif prototype_node.bl_idname == 'GeometryCirclePrimitive':
  574. return classes["CirclePrimitive"]
  575. # every node before this point is not guarenteed to follow the pattern
  576. # but every node not checked above does follow the pattern.
  577. try:
  578. return classes[ prototype_node.bl_idname ]
  579. except KeyError:
  580. # prGreen(prototype_node.bl_idname)
  581. # prWhite(classes.keys())
  582. pass
  583. if prototype_node.bl_idname in [
  584. "NodeReroute",
  585. "NodeGroupInput",
  586. "NodeGroupOutput",
  587. "MantisNodeGroup",
  588. "NodeFrame",
  589. "MantisSchemaGroup",
  590. ]:
  591. return None
  592. prRed(prototype_node.bl_idname)
  593. raise RuntimeError(wrapOrange("Failed to create node container for: ")+wrapRed("%s" % prototype_node.bl_idname))
  594. return None
  595. # This is really, really stupid way to do this
  596. def gen_nc_input_for_data(socket):
  597. # Class List #TODO deduplicate
  598. from . import xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers
  599. from .internal_containers import NoOpNode
  600. classes = {}
  601. for module in [xForm_containers, link_containers, misc_containers, primitives_containers, deformer_containers, math_containers, schema_containers]:
  602. for cls in module.TellClasses():
  603. classes[cls.__name__] = cls
  604. #
  605. socket_class_map = {
  606. "MatrixSocket" : classes["InputMatrix"],
  607. "xFormSocket" : None,
  608. "RelationshipSocket" : NoOpNode,
  609. "DeformerSocket" : NoOpNode,
  610. "GeometrySocket" : classes["InputExistingGeometryData"],
  611. "EnableSocket" : classes["InputBoolean"],
  612. "HideSocket" : classes["InputBoolean"],
  613. #
  614. "DriverSocket" : None,
  615. "DriverVariableSocket" : None,
  616. "FCurveSocket" : None,
  617. "KeyframeSocket" : None,
  618. "BoneCollectionSocket" : classes["InputString"],
  619. #
  620. "xFormParameterSocket" : None,
  621. "ParameterBoolSocket" : classes["InputBoolean"],
  622. "ParameterIntSocket" : classes["InputFloat"], #TODO: make an Int node for this
  623. "ParameterFloatSocket" : classes["InputFloat"],
  624. "ParameterVectorSocket" : classes["InputVector"],
  625. "ParameterStringSocket" : classes["InputString"],
  626. #
  627. "TransformSpaceSocket" : classes["InputTransformSpace"],
  628. "BooleanSocket" : classes["InputBoolean"],
  629. "BooleanThreeTupleSocket" : classes["InputBooleanThreeTuple"],
  630. "RotationOrderSocket" : classes["InputRotationOrder"],
  631. "QuaternionSocket" : None,
  632. "QuaternionSocketAA" : None,
  633. "IntSocket" : classes["InputFloat"],
  634. "StringSocket" : classes["InputString"],
  635. #
  636. "BoolUpdateParentNode" : classes["InputBoolean"],
  637. "IKChainLengthSocket" : classes["InputFloat"],
  638. "EnumInheritScale" : classes["InputString"],
  639. "EnumRotationMix" : classes["InputString"],
  640. "EnumRotationMixCopyTransforms" : classes["InputString"],
  641. "EnumMaintainVolumeStretchTo" : classes["InputString"],
  642. "EnumRotationStretchTo" : classes["InputString"],
  643. "EnumTrackAxis" : classes["InputString"],
  644. "EnumUpAxis" : classes["InputString"],
  645. "EnumLockAxis" : classes["InputString"],
  646. "EnumLimitMode" : classes["InputString"],
  647. "EnumYScaleMode" : classes["InputString"],
  648. "EnumXZScaleMode" : classes["InputString"],
  649. "EnumCurveSocket" : classes["InputString"],
  650. "EnumMetaRigSocket" : classes["InputString"],
  651. # Deformers
  652. "EnumSkinning" : classes["InputString"],
  653. #
  654. "FloatSocket" : classes["InputFloat"],
  655. "FloatFactorSocket" : classes["InputFloat"],
  656. "FloatPositiveSocket" : classes["InputFloat"],
  657. "FloatAngleSocket" : classes["InputFloat"],
  658. "VectorSocket" : classes["InputVector"],
  659. "VectorEulerSocket" : classes["InputVector"],
  660. "VectorTranslationSocket" : classes["InputVector"],
  661. "VectorScaleSocket" : classes["InputVector"],
  662. # Drivers
  663. "EnumDriverVariableType" : classes["InputString"],
  664. "EnumDriverVariableEvaluationSpace" : classes["InputString"],
  665. "EnumDriverRotationMode" : classes["InputString"],
  666. "EnumDriverType" : classes["InputString"],
  667. "EnumKeyframeInterpTypeSocket" : classes["InputString"],
  668. "EnumKeyframeBezierHandleTypeSocket" : classes["InputString"],
  669. # Math
  670. "MathFloatOperation" : classes["InputString"],
  671. "MathVectorOperation" : classes["InputString"],
  672. "MatrixTransformOperation" : classes["InputString"],
  673. # Schema
  674. "WildcardSocket" : None,
  675. }
  676. return socket_class_map.get(socket.bl_idname, None)
  677. ####################################
  678. # CURVE STUFF
  679. ####################################
  680. def rotate(l, n):
  681. if ( not ( isinstance(n, int) ) ): #print an error if n is not an int:
  682. raise TypeError("List slice must be an int, not float.")
  683. return l[n:] + l[:n]
  684. #from stack exchange, thanks YXD
  685. # this stuff could be branchless but I don't use it much TODO
  686. def cap(val, maxValue):
  687. if (val > maxValue):
  688. return maxValue
  689. return val
  690. def capMin(val, minValue):
  691. if (val < minValue):
  692. return minValue
  693. return val
  694. # def wrap(val, min=0, max=1):
  695. # raise NotImplementedError
  696. #wtf this doesn't do anything even remotely similar to wrap, or useful in
  697. # HACK BAD FIXME UNBREAK ME BAD
  698. # I don't understand what this function does but I am using it in multiple places?
  699. def wrap(val, maxValue, minValue = None):
  700. if (val > maxValue):
  701. return (-1 * ((maxValue - val) + 1))
  702. if ((minValue) and (val < minValue)):
  703. return (val + maxValue)
  704. return val
  705. #TODO clean this up
  706. def layerMaskCompare(mask_a, mask_b):
  707. compare = 0
  708. for a, b in zip(mask_a, mask_b):
  709. if (a != b):
  710. compare+=1
  711. if (compare == 0):
  712. return True
  713. return False
  714. def lerpVal(a, b, fac = 0.5):
  715. return a + ( (b-a) * fac)
  716. def RibbonMeshEdgeLengths(m, ribbon):
  717. tE = ribbon[0]; bE = ribbon[1]; c = ribbon[2]
  718. lengths = []
  719. for i in range( len( tE ) ): #tE and bE are same length
  720. if (c == True):
  721. v1NextInd = tE[wrap((i+1), len(tE) - 1)]
  722. else:
  723. v1NextInd = tE[cap((i+1) , len(tE) - 1 )]
  724. v1 = m.vertices[tE[i]]; v1Next = m.vertices[v1NextInd]
  725. if (c == True):
  726. v2NextInd = bE[wrap((i+1), len(bE) - 1)]
  727. else:
  728. v2NextInd = bE[cap((i+1) , len(bE) - 1 )]
  729. v2 = m.vertices[bE[i]]; v2Next = m.vertices[v2NextInd]
  730. v = v1.co.lerp(v2.co, 0.5); vNext = v1Next.co.lerp(v2Next.co, 0.5)
  731. # get the center, edges may not be straight so total length
  732. # of one edge may be more than the ribbon center's length
  733. lengths.append(( v - vNext ).length)
  734. return lengths
  735. def EnsureCurveIsRibbon(crv, defaultRadius = 0.1):
  736. crvRadius = 0
  737. if (crv.data.bevel_depth == 0):
  738. crvRadius = crv.data.extrude
  739. else: #Set ribbon from bevel depth
  740. crvRadius = crv.data.bevel_depth
  741. crv.data.bevel_depth = 0
  742. crv.data.extrude = crvRadius
  743. if (crvRadius == 0):
  744. crv.data.extrude = defaultRadius
  745. def SetRibbonData(m, ribbon):
  746. #maybe this could be incorporated into the DetectWireEdges function?
  747. #maybe I can check for closed poly curves here? under what other circumstance
  748. # will I find the ends of the wire have identical coordinates?
  749. ribbonData = []
  750. tE = ribbon[0].copy(); bE = ribbon[1].copy()# circle = ribbon[2]
  751. #
  752. lengths = RibbonMeshEdgeLengths(m, ribbon)
  753. lengths.append(0)
  754. totalLength = sum(lengths)
  755. # m.calc_normals() #calculate normals
  756. # it appears this has been removed.
  757. for i, (t, b) in enumerate(zip(tE, bE)):
  758. ind = wrap( (i + 1), len(tE) - 1 )
  759. tNext = tE[ind]; bNext = bE[ind]
  760. ribbonData.append( ( (t,b), (tNext, bNext), lengths[i] ) )
  761. #if this is a circle, the last v in vertData has a length, otherwise 0
  762. return ribbonData, totalLength
  763. def mesh_from_curve(crv, context,):
  764. """Utility function for converting a mesh to a curve
  765. which will return the correct mesh even with modifiers"""
  766. import bpy
  767. if (len(crv.modifiers) > 0):
  768. do_unlink = False
  769. if (not context.scene.collection.all_objects.get(crv.name)):
  770. context.collection.objects.link(crv) # i guess this forces the dg to update it?
  771. do_unlink = True
  772. dg = context.view_layer.depsgraph
  773. # just gonna modify it for now lol
  774. EnsureCurveIsRibbon(crv)
  775. # try:
  776. dg.update()
  777. mOb = crv.evaluated_get(dg)
  778. m = bpy.data.meshes.new_from_object(mOb)
  779. m.name=crv.data.name+'_mesh'
  780. if (do_unlink):
  781. context.collection.objects.unlink(crv)
  782. return m
  783. # except: #dg is None?? # FIX THIS BUG BUG BUG
  784. # print ("Warning: could not apply modifiers on curve")
  785. # return bpy.data.meshes.new_from_object(crv)
  786. else: # (ಥ﹏ಥ) why can't I just use this !
  787. # for now I will just do it like this
  788. EnsureCurveIsRibbon(crv)
  789. return bpy.data.meshes.new_from_object(crv)
  790. def DetectRibbon(f, bm, skipMe):
  791. fFirst = f.index
  792. cont = True
  793. circle = False
  794. tEdge, bEdge = [],[]
  795. while (cont == True):
  796. skipMe.add(f.index)
  797. tEdge.append (f.loops[0].vert.index) # top-left
  798. bEdge.append (f.loops[3].vert.index) # bottom-left
  799. nEdge = bm.edges.get([f.loops[1].vert, f.loops[2].vert])
  800. nFaces = nEdge.link_faces
  801. if (len(nFaces) == 1):
  802. cont = False
  803. else:
  804. for nFace in nFaces:
  805. if (nFace != f):
  806. f = nFace
  807. break
  808. if (f.index == fFirst):
  809. cont = False
  810. circle = True
  811. if (cont == False): # we've reached the end, get the last two:
  812. tEdge.append (f.loops[1].vert.index) # top-right
  813. bEdge.append (f.loops[2].vert.index) # bottom-right
  814. # this will create a loop for rings --
  815. # "the first shall be the last and the last shall be first"
  816. return (tEdge,bEdge,circle)
  817. def DetectRibbons(m, fReport = None):
  818. # Returns list of vertex indices belonging to ribbon mesh edges
  819. # NOTE: this assumes a mesh object with only ribbon meshes
  820. # ---DO NOT call this script with a mesh that isn't a ribbon!--- #
  821. import bmesh
  822. bm = bmesh.new()
  823. bm.from_mesh(m)
  824. mIslands, mIsland = [], []
  825. skipMe = set()
  826. bm.faces.ensure_lookup_table()
  827. #first, get a list of mesh islands
  828. for f in bm.faces:
  829. if (f.index in skipMe):
  830. continue #already done here
  831. checkMe = [f]
  832. while (len(checkMe) > 0):
  833. facesFound = 0
  834. for f in checkMe:
  835. if (f.index in skipMe):
  836. continue #already done here
  837. mIsland.append(f)
  838. skipMe.add(f.index)
  839. for e in f.edges:
  840. checkMe += e.link_faces
  841. if (facesFound == 0):
  842. #this is the last iteration
  843. mIslands.append(mIsland)
  844. checkMe, mIsland = [], []
  845. ribbons = []
  846. skipMe = set() # to store ends already checked
  847. for mIsl in mIslands:
  848. ribbon = None
  849. first = float('inf')
  850. for f in mIsl:
  851. if (f.index in skipMe):
  852. continue #already done here
  853. if (f.index < first):
  854. first = f.index
  855. adjF = 0
  856. for e in f.edges:
  857. adjF+= (len(e.link_faces) - 1)
  858. # every face other than this one is added to the list
  859. if (adjF == 1):
  860. ribbon = (DetectRibbon(f, bm, skipMe) )
  861. break
  862. if (ribbon == None):
  863. ribbon = (DetectRibbon(bm.faces[first], bm, skipMe) )
  864. ribbons.append(ribbon)
  865. # print (ribbons)
  866. return ribbons
  867. def data_from_ribbon_mesh(m, factorsList, mat, ribbons = None, fReport = None):
  868. #Note, factors list should be equal in length the the number of wires
  869. #Now working for multiple wires, ugly tho
  870. if (ribbons == None):
  871. ribbons = DetectRibbons(m, fReport=fReport)
  872. if (ribbons is None):
  873. if (fReport):
  874. fReport(type = {'ERROR'}, message="No ribbon to get data from.")
  875. else:
  876. print ("No ribbon to get data from.")
  877. return None
  878. ret = []
  879. for factors, ribbon in zip(factorsList, ribbons):
  880. points = []
  881. widths = []
  882. normals = []
  883. ribbonData, totalLength = SetRibbonData(m, ribbon)
  884. for fac in factors:
  885. if (fac == 0):
  886. data = ribbonData[0]
  887. curFac = 0
  888. elif (fac == 1):
  889. data = ribbonData[-1]
  890. curFac = 0
  891. else:
  892. targetLength = totalLength * fac
  893. data = ribbonData[0]
  894. curLength = 0
  895. for ( (t, b), (tNext, bNext), length,) in ribbonData:
  896. if (curLength >= targetLength):
  897. break
  898. curLength += length
  899. data = ( (t, b), (tNext, bNext), length,)
  900. targetLengthAtEdge = (curLength - targetLength)
  901. if (targetLength == 0):
  902. curFac = 0
  903. elif (targetLength == totalLength):
  904. curFac = 1
  905. else:
  906. try:
  907. curFac = 1 - (targetLengthAtEdge/ data[2]) #length
  908. except ZeroDivisionError:
  909. curFac = 0
  910. if (fReport):
  911. fReport(type = {'WARNING'}, message="Division by Zero.")
  912. else:
  913. prRed ("Division by Zero Error in evaluating data from curve.")
  914. t1 = m.vertices[data[0][0]]; b1 = m.vertices[data[0][1]]
  915. t2 = m.vertices[data[1][0]]; b2 = m.vertices[data[1][1]]
  916. #location
  917. loc1 = (t1.co).lerp(b1.co, 0.5)
  918. loc2 = (t2.co).lerp(b2.co, 0.5)
  919. #width
  920. w1 = (t1.co - b1.co).length/2
  921. w2 = (t2.co - b2.co).length/2 #radius, not diameter
  922. #normal
  923. n1 = (t1.normal).slerp(b1.normal, 0.5)
  924. n2 = (t1.normal).slerp(b2.normal, 0.5)
  925. if ((data[0][0] > data[1][0]) and (ribbon[2] == False)):
  926. curFac = 0
  927. #don't interpolate if at the end of a ribbon that isn't circular
  928. if ( 0 < curFac < 1):
  929. outPoint = loc1.lerp(loc2, curFac)
  930. outNorm = n1.lerp(n2, curFac)
  931. outWidth = w1 + ( (w2-w1) * curFac)
  932. elif (curFac <= 0):
  933. outPoint = loc1.copy()
  934. outNorm = n1
  935. outWidth = w1
  936. elif (curFac >= 1):
  937. outPoint = loc2.copy()
  938. outNorm = n2
  939. outWidth = w2
  940. outPoint = mat @ outPoint
  941. outNorm.normalize()
  942. points.append ( outPoint.copy() ) #copy because this is an actual vertex location
  943. widths.append ( outWidth )
  944. normals.append( outNorm )
  945. ret.append( (points, widths, normals) )
  946. return ret # this is a list of tuples containing three lists
  947. #This bisection search is generic, and it searches based on the
  948. # magnitude of the error, rather than the sign.
  949. # If the sign of the error is meaningful, a simpler function
  950. # can be used.
  951. def do_bisect_search_by_magnitude(
  952. owner,
  953. attribute,
  954. index = None,
  955. test_function = None,
  956. modify = None,
  957. max_iterations = 10000,
  958. threshold = 0.0001,
  959. thresh2 = 0.0005,
  960. context = None,
  961. update_dg = None,
  962. ):
  963. from math import floor
  964. i = 0; best_so_far = 0; best = float('inf')
  965. min = 0; center = max_iterations//2; max = max_iterations
  966. # enforce getting the absolute value, in case the function has sign information
  967. # The sign may be useful in a sign-aware bisect search, but this one is more robust!
  968. test = lambda : abs(test_function(owner, attribute, index, context = context,))
  969. while (i <= max_iterations):
  970. upper = (max - ((max-center))//2)
  971. modify(owner, attribute, index, upper, context = context); error1 = test()
  972. lower = (center - ((center-min))//2)
  973. modify(owner, attribute, index, lower, context = context); error2 = test()
  974. if (error1 < error2):
  975. min = center
  976. center, check = upper, upper
  977. error = error1
  978. else:
  979. max = center
  980. center, check = lower, lower
  981. error = error2
  982. if (error <= threshold) or (min == max-1):
  983. break
  984. if (error < thresh2):
  985. j = min
  986. while (j < max):
  987. modify(owner, attribute, index, j * 1/max_iterations, context = context)
  988. error = test()
  989. if (error < best):
  990. best_so_far = j; best = error
  991. if (error <= threshold):
  992. break
  993. j+=1
  994. else: # loop has completed without finding a solution
  995. i = best_so_far; error = test()
  996. modify(owner, attribute, index, best_so_far, context = context)
  997. break
  998. if (error < best):
  999. best_so_far = check; best = error
  1000. i+=1
  1001. if update_dg:
  1002. update_dg.update()
  1003. else: # Loop has completed without finding a solution
  1004. i = best_so_far
  1005. modify(owner, attribute, best_so_far, context = context); i+=1