utilities.py 42 KB

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