utilities.py 40 KB

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