utilities.py 40 KB

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