utilities.py 40 KB

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