utilities.py 42 KB

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