base_definitions.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. #Mantis Nodes Base
  2. import bpy
  3. from bpy.props import (BoolProperty, StringProperty, EnumProperty, CollectionProperty, \
  4. IntProperty, IntVectorProperty, PointerProperty, BoolVectorProperty)
  5. from . import ops_nodegroup
  6. from bpy.types import NodeTree, Node, PropertyGroup, Operator, UIList, Panel
  7. from .utilities.utilities import (prRed, prGreen, prPurple, prWhite,
  8. prOrange,
  9. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  10. wrapOrange,)
  11. from .utilities.utilities import get_socket_maps, get_socket_overlay_info, do_relink
  12. from .mantis_dataclasses import MantisSocketTemplate
  13. MANTIS_VERSION_MAJOR=0
  14. MANTIS_VERSION_MINOR=13
  15. MANTIS_VERSION_SUB=5
  16. FLOAT_EPSILON=0.0001 # used to check against floating point inaccuracy
  17. links_sort_key= lambda a : (-a.multi_input_sort_id, -a.sub_sort_id)
  18. selection_sync_node_to_object = {} # what objects a node spawns
  19. selection_sync_object_to_node = {} # what node an object comes from
  20. # The reroute cache is used to accelerate reading reroute nodes
  21. # it uses the tree name and hash to ensure reroutes are only updated when needed
  22. # reroutes recursively find their source and remember it
  23. reroute_cache = {}
  24. def TellClasses():
  25. #Why use a function to do this? Because I don't need every class to register.
  26. return [ MantisTree,
  27. SchemaTree,
  28. MantisNodeGroup,
  29. SchemaGroup,
  30. ]
  31. def error_popup_draw(self, context):
  32. self.layout.label(text="Error executing tree. See Console.")
  33. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  34. from os import environ
  35. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  36. # thank you, Sverchok
  37. def valid_interface_types(cls : NodeTree, socket_idname : str):
  38. from .socket_definitions import tell_valid_bl_idnames, TellClasses
  39. #TODO: do the versioning code to handle this so it can be in all versions
  40. if bpy.app.version <= (4,4,0): # should work in 4.4.1
  41. return socket_idname in [cls.bl_idname for cls in TellClasses()]
  42. elif bpy.app.version == (4,5,0): # workaround for a BUG
  43. return ['NodeSocketGeometry']
  44. else: # once versioning is finished this will be unnecesary.
  45. return socket_idname in tell_valid_bl_idnames()
  46. def fix_reroute_colors(tree):
  47. context = bpy.context
  48. if any((tree.is_executing, tree.is_exporting, tree.do_live_update==False, context.space_data is None) ):
  49. return
  50. from .utilities.utilities import find_reroute_start_socket
  51. from .socket_definitions import MantisSocket
  52. reroutes_without_color = []
  53. for n in tree.nodes:
  54. if n.bl_idname=='NodeReroute' and n.inputs[0].bl_idname == "NodeSocketColor":
  55. reroutes_without_color.append(n)
  56. try:
  57. while reroutes_without_color:
  58. rr = reroutes_without_color.pop()
  59. if rr.inputs[0].is_linked:
  60. link = rr.inputs[0].links[0]
  61. socket = find_reroute_start_socket(rr)
  62. if isinstance(socket, MantisSocket):
  63. rr.socket_idname = socket.bl_idname
  64. except Exception as e:
  65. print(wrapOrange("WARN: Updating reroute color failed with exception: ")+wrapWhite(f"{e.__class__.__name__}"))
  66. #functions to identify the state of the system using hashes
  67. # this function runs a lot so it should be optimized as well as possible.
  68. def hash_tree(tree, recurse=True):
  69. trees=set(); links=[]; hash_data=""
  70. for node in tree.nodes:
  71. hash_data+=str(node.name)
  72. if recurse and hasattr(node, 'node_tree') and node.node_tree:
  73. trees.add(node.node_tree)
  74. for other_tree in trees:
  75. hash_data+=str(hash_tree(other_tree))
  76. for link in tree.links:
  77. links.append( link.from_node.name+link.from_socket.name+
  78. link.to_node.name+link.to_socket.name+
  79. str(link.multi_input_sort_id) )
  80. links.sort(); hash_data+=''.join(links)
  81. return hash(hash_data)
  82. # TODO: I should see if I can make these work without every using NodeSocket.links
  83. # as that getter is very slow at scale
  84. # however with the cache in place it is probably negligible
  85. def update_reroute_cache_item_source_recursively(reroute, tree_cache, source):
  86. # find all the inputs to this reroute and update their destination sets
  87. # every reroute ancestor pushes to this destination... but not every recursive-child
  88. # of the root reroute necessarily does, so pushing back like this is right
  89. # since each reroute node only has one ancestor, this is easy
  90. from .mantis_dataclasses import RerouteCacheItem
  91. tree= reroute.id_data
  92. reroutes = {reroute}
  93. while(reroutes):
  94. reroute = reroutes.pop()
  95. # for making a new cache item
  96. if (cache_object := tree_cache.get(reroute.name)) is None:
  97. cache_object = RerouteCacheItem(
  98. reroute_name=reroute.name,
  99. reroute_tree_name=tree.name,
  100. )
  101. tree_cache[reroute.name] = cache_object
  102. cache_object.source = source
  103. if rr_links := reroute.outputs[0].links: # reroutes are always single-output
  104. for l in rr_links: # with potentially many links
  105. if l.to_node.bl_idname == 'NodeReroute':
  106. reroutes.add(l.to_node)
  107. def update_reroute_cache_item_destination_recursively(reroute, tree_cache, destination):
  108. # find all the inputs to this reroute and update their destination sets
  109. # every reroute ancestor pushes to this destination... but not every recursive-child
  110. # of the root reroute necessarily does, so pushing back like this is right
  111. # since each reroute node only has one ancestor, this is easy
  112. from .mantis_dataclasses import RerouteCacheItem
  113. tree= reroute.id_data
  114. while(reroute):
  115. # for making a new cache item
  116. if (cache_object := tree_cache.get(reroute.name)) is None:
  117. cache_object = RerouteCacheItem(
  118. reroute_name=reroute.name,
  119. reroute_tree_name=tree.name,
  120. destinations= {destination},
  121. )
  122. tree_cache[reroute.name] = cache_object
  123. else:
  124. cache_object.destinations.add(destination)
  125. # Odd: if I check reroute.inputs[0].is_linked with live updates, CRASH.
  126. if rr_links := reroute.inputs[0].links:
  127. # reroutes are always single-input with at most 1 link
  128. if (l := rr_links[0]).from_node == 'NodeReroute':
  129. reroute = l.from_node
  130. continue
  131. reroute = None
  132. # Update the reroute cache from the link
  133. # NOTE this is updated as the user adds links by the node.insert_link() callback
  134. def reroute_cache_handle_link(tree, tree_cache, link):
  135. from .mantis_dataclasses import RerouteCacheItem
  136. # if it is a link to or from a reroute, add or update the cache item
  137. # first check if the cache item is stale
  138. # then try and fill the source and destination - make sure to recursively fill them
  139. # if it isn't connected to a source or destination, it's part of a network
  140. # We only need to check the ends, and we can do both the destination and source
  141. # passes simultaneously since they don't depend on each other.
  142. # NOTE that we use socket index to make things explicit and fast
  143. if link.from_node.bl_idname == 'NodeReroute' and link.to_node.bl_idname != 'NodeReroute':
  144. other_node = link.to_node
  145. other_socket = link.to_socket
  146. for socket_index, check_socket in enumerate(other_node.inputs):
  147. if check_socket.identifier == other_socket.identifier: break
  148. else:
  149. raise RuntimeError("Error, cannot make reroute cache for link: "
  150. f"{link.from_node.name}:{link.from_socket.name} ==>"
  151. f"{link.to_node.name}:{link.to_socket.name}")
  152. reroute = link.from_node
  153. destination = (other_node.name, socket_index)
  154. if (cache_object := tree_cache.get(reroute.name)) is None:
  155. cache_object = RerouteCacheItem(
  156. reroute_name=reroute.name,
  157. reroute_tree_name=tree.name,
  158. destinations= {destination},
  159. )
  160. tree_cache[reroute.name]=cache_object
  161. update_reroute_cache_item_destination_recursively(reroute, tree_cache,
  162. destination=destination)
  163. elif link.from_node.bl_idname != 'NodeReroute' and link.to_node.bl_idname == 'NodeReroute':
  164. other_node = link.from_node
  165. other_socket = link.from_socket
  166. for socket_index, check_socket in enumerate(other_node.outputs):
  167. if check_socket.identifier == other_socket.identifier: break
  168. else:
  169. raise RuntimeError("Error, cannot make reroute cache for link: "
  170. f"{link.from_node.name}:{link.from_socket.name} ==>"
  171. f"{link.to_node.name}:{link.to_socket.name}")
  172. reroute = link.to_node
  173. source = (link.from_node.name, socket_index)
  174. if (cache_object := tree_cache.get(reroute.name)) is None:
  175. cache_object = RerouteCacheItem(
  176. reroute_name=reroute.name,
  177. reroute_tree_name=tree.name,
  178. source = source,
  179. )
  180. tree_cache[reroute.name]=cache_object
  181. update_reroute_cache_item_source_recursively(reroute, tree_cache,
  182. source=source)
  183. def build_reroute_cache(tree, links):
  184. # we'll track this to know if a tree update should invalidate the hash on incremental update
  185. tree.number_of_reroute_links = 0
  186. # make sure to clear the previous cache or confusing things will happen
  187. tree_cache = {}; reroute_cache[tree.name] = tree_cache
  188. tree_cache['_MANTIS_RESERVED_TREE_HASH'] = tree.hash
  189. for link in links:
  190. if link.from_node.bl_idname == 'NodeReroute' or link.to_node.bl_idname == 'NodeReroute':
  191. tree.number_of_reroute_links += 1
  192. reroute_cache_handle_link(tree, tree_cache, link)
  193. def tree_update_common(tree): # set the reroute colors
  194. if tree.is_quitting: return
  195. if (bpy.app.version == (4,4,0)): # CTD bug in that version
  196. return
  197. fix_reroute_colors(tree)
  198. # intialize it if e.g the tree is new.
  199. if (tree_cache := reroute_cache.get(tree.name)) is None:
  200. tree_cache = {}; reroute_cache[tree.name] = tree_cache
  201. # events fire in this order:
  202. # - node.insert_link (one for each node)
  203. # - node.update (one for each node)
  204. # - tree.update
  205. # so if the node's insert_link handled things, we don't need to check
  206. tree.hash = str(hash_tree(tree, recurse=False))
  207. if tree.reroute_link_handled: # we can update the hash, it's still good.
  208. if tree_cache := reroute_cache.get(tree.name):
  209. tree_cache["_MANTIS_RESERVED_TREE_HASH"]=tree.hash
  210. tree.reroute_link_handled = False # always make sure to reset the flag
  211. else:
  212. reroute_links = []
  213. # set the UI tree hash for e.g. reroute cache
  214. for link in tree.links:
  215. if link.from_node.bl_idname == 'NodeReroute' or link.to_node.bl_idname == 'NodeReroute':
  216. reroute_links.append(link)
  217. if len(reroute_links) == tree.number_of_reroute_links:
  218. if tree_cache := reroute_cache.get(tree.name): # we can update the hash, it's still good.
  219. tree_cache["_MANTIS_RESERVED_TREE_HASH"] = tree.hash
  220. else: # there is no cache after all. How did that happen?
  221. build_reroute_cache(tree, reroute_links)
  222. # NOTE I put a lot of effort into catching deleted links but it just isn't practical
  223. # to catch this and it is almost free to rebuild the cache.
  224. else:
  225. build_reroute_cache(tree, reroute_links)
  226. # reset the count but do not update the hash.
  227. tree.number_of_reroute_links = len(reroute_links)
  228. class MantisTree(NodeTree):
  229. '''A custom node tree type that will show up in the editor type list'''
  230. bl_idname = 'MantisTree'
  231. bl_label = "Rigging Nodes"
  232. bl_icon = 'OUTLINER_OB_ARMATURE'
  233. tree_valid:BoolProperty(default=False)
  234. hash:StringProperty(default='') # use for UI updates, reroute cache
  235. hash_recursive:StringProperty(default='') # use for checking Mantis state
  236. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  237. # operator settings for re-exporting the tree.
  238. filepath:StringProperty(default="", subtype='FILE_PATH')
  239. export_all_subtrees_together:BoolProperty(default=True)
  240. #
  241. is_executing:BoolProperty(default=False)
  242. is_exporting:BoolProperty(default=False)
  243. is_quitting:BoolProperty(default=False)
  244. execution_id:StringProperty(default='')
  245. # prev_execution_id:StringProperty(default='')
  246. mantis_version:IntVectorProperty(default=[
  247. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR-1, MANTIS_VERSION_SUB-1])
  248. # this prevents the node group from executing on the next depsgraph update
  249. # because I don't always have control over when the dg upadte happens.
  250. prevent_next_exec:BoolProperty(default=False)
  251. #added to work around a bug in 4.5.0 LTS
  252. interface_helper : StringProperty(default='')
  253. # for reroute cache, to check if it is still good
  254. number_of_reroute_links : IntProperty(default=0)
  255. # flag to indicate a link was already handled this update
  256. reroute_link_handled : BoolProperty(default=False)
  257. parsed_tree={}
  258. # NOTE that these are class properties that should be serialized
  259. # to per-instance bpy properties when switching trees.
  260. # The class properties should, however, be associated to specific
  261. # trees by name so that the user can edit multiple trees at once.
  262. # Selection Sync Dicts
  263. node_to_object_map = {}
  264. object_to_node_map = {}
  265. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  266. @classmethod
  267. def valid_socket_type(cls : NodeTree, socket_idname: str):
  268. return valid_interface_types(cls, socket_idname)
  269. def update(self):
  270. tree_update_common(self)
  271. def update_tree(self, context = None, force=False, error_popups=False):
  272. if self.is_exporting:
  273. return
  274. my_hash = str( hash_tree(self) )
  275. my_ui_hash = str( hash_tree(self, recurse=False))
  276. tree_cache = reroute_cache.get(self.name)
  277. if tree_cache['_MANTIS_RESERVED_TREE_HASH'] != my_ui_hash:
  278. build_reroute_cache(self, self.links) # somehow it became invalid, rebuild it.
  279. if (my_hash != self.hash_recursive) or force:
  280. self.hash_recursive = my_hash
  281. self.is_executing = True
  282. from .execution import readtree
  283. prGreen("Validating Tree: %s" % self.name)
  284. try:
  285. import bpy # I am importing here so that the context passed in
  286. # is used for display update... but I always want to do this
  287. scene = bpy.context.scene
  288. scene.render.use_lock_interface = True
  289. self.parsed_tree = readtree.parse_tree(self, error_popups)
  290. if context:
  291. self.display_update(context)
  292. self.tree_valid = bool(self.parsed_tree)
  293. except Exception as e:
  294. prRed("Failed to update node tree due to error.")
  295. self.tree_valid = False
  296. self.hash_recursive='' # unset the hash to mark the tree as un-parsed.
  297. raise e
  298. finally:
  299. scene.render.use_lock_interface = False
  300. self.is_executing = False
  301. if self.parsed_tree is None:
  302. self.parsed_tree = {}
  303. return 1 # failure
  304. return 0 # success
  305. def display_update(self, context):
  306. if self.is_exporting:
  307. return
  308. self.is_executing = True
  309. try:
  310. current_tree = bpy.context.space_data.path[-1].node_tree
  311. for node in current_tree.nodes:
  312. if hasattr(node, "display_update"):
  313. try:
  314. node.display_update(self.parsed_tree, context)
  315. except Exception as e:
  316. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  317. finally:
  318. self.is_executing = False
  319. # TODO: deal with invalid links properly.
  320. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  321. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  322. def execute_tree(self,context, error_popups = False, profile=False):
  323. self.prevent_next_exec = False
  324. if not self.hash_recursive:
  325. return
  326. if not self.parsed_tree:
  327. return
  328. if self.is_exporting or self.is_executing:
  329. return
  330. prGreen("Executing Tree: %s" % self.name)
  331. self.is_executing = True
  332. from .execution import readtree
  333. try:
  334. context.scene.render.use_lock_interface = True
  335. readtree.execute_tree(self.parsed_tree, self, context, error_popups, profile=profile)
  336. except RecursionError as e:
  337. prRed("Recursion error while parsing tree.")
  338. finally:
  339. context.scene.render.use_lock_interface = False
  340. self.is_executing = False
  341. class SchemaTree(NodeTree):
  342. '''A node tree representing a schema to generate a Mantis tree'''
  343. bl_idname = 'SchemaTree'
  344. bl_label = "Rigging Nodes Schema"
  345. bl_icon = 'RIGID_BODY_CONSTRAINT'
  346. # these are only needed for consistent interface, but should not be used
  347. do_live_update:BoolProperty(default=True) # default to true so that updates work
  348. is_executing:BoolProperty(default=False)
  349. is_exporting:BoolProperty(default=False)
  350. is_quitting:BoolProperty(default=False)
  351. mantis_version:IntVectorProperty(default=[
  352. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  353. # see the note in MantisTree
  354. interface_helper : StringProperty(default='')
  355. # for reroute cache, to check if it is still good
  356. number_of_reroute_links : IntProperty(default=0)
  357. # flag to indicate a link was already handled this update
  358. reroute_link_handled : BoolProperty(default=False)
  359. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  360. @classmethod
  361. def valid_socket_type(cls : NodeTree, socket_idname: str):
  362. return valid_interface_types(cls, socket_idname)
  363. def update(self):
  364. tree_update_common(self)
  365. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  366. # TODO: I want to avoid doing any kind of class mutation at runtime
  367. # so in the future I will try to do this directly rather than
  368. # running this function once for each class while registering
  369. # however this is not very important for UI classes since they
  370. # are not a performance bottleneck.
  371. def mantis_class_from_library(library, class_name):
  372. from importlib import import_module
  373. return getattr(import_module(library, package=mantis_root), class_name)
  374. class MantisUINode:
  375. """
  376. This class contains the common user-interface features of Mantis nodes.
  377. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  378. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  379. """
  380. # blender stuff, I'll need to split this into a mixin class later
  381. bl_icon = 'NODE'
  382. initialized : bpy.props.BoolProperty(default = False)
  383. #
  384. mantis_node_class_name=''
  385. mantis_class=None
  386. socket_templates=None
  387. @classmethod
  388. def poll(cls, ntree):
  389. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  390. def init(self, context):
  391. self.init_sockets(self.socket_templates)
  392. self.initialized = True
  393. def init_sockets(self, socket_templates : tuple[MantisSocketTemplate]):
  394. for template in socket_templates:
  395. collection = self.outputs
  396. if template.is_input:
  397. collection = self.inputs
  398. identifier = template.name
  399. if template.identifier:
  400. identifier = template.identifier
  401. use_multi_input = template.use_multi_input if template.is_input else False
  402. socket = collection.new(
  403. template.bl_idname,
  404. template.name,
  405. identifier=identifier,
  406. use_multi_input=use_multi_input
  407. )
  408. socket.hide= template.hide
  409. if template.category:
  410. from . import DOERROR
  411. # a custom property for the UI functions to use.
  412. if hasattr(socket, "category"):
  413. socket.category = template.category
  414. elif DOERROR:
  415. print (f"WARN: socket type {socket.bl_idname} has no category attribute")
  416. if template.default_value is not None:
  417. socket.default_value = template.default_value
  418. # this can throw a TypeError - it is the caller's
  419. # responsibility to send the right type.
  420. if template.use_multi_input: # this is an array
  421. socket.display_shape = 'SQUARE_DOT'
  422. def insert_link(self, link):
  423. if (bpy.app.version == (4, 4, 0)):
  424. return # this causes a crash due to a bug.
  425. tree = self.id_data
  426. if tree.reroute_link_handled: return
  427. if ( link.from_node.bl_idname == 'NodeReroute' or
  428. link.to_node.bl_idname == 'NodeReroute' ):
  429. tree.number_of_reroute_links+=1
  430. reroute_cache_handle_link(tree=tree,
  431. tree_cache=reroute_cache.get(tree.name), link=link)
  432. tree.reroute_link_handled = True
  433. # NOTE
  434. # MantisUINode has no proper mantis libraryclass on its own, so:
  435. # register()'s are in SUBclasses; they have to run AFTER library is defined
  436. class SchemaUINode(MantisUINode):
  437. is_updating:BoolProperty(default=False)
  438. @classmethod
  439. def register(cls):
  440. cls.mantis_class = mantis_class_from_library('.schema_nodes', cls.mantis_node_class_name)
  441. class LinkNode(MantisUINode):
  442. mantis_node_library='.link_nodes'
  443. category_color=[0.5,0.5,0.5]
  444. @classmethod
  445. def register(cls):
  446. cls.mantis_class = mantis_class_from_library('.link_nodes', cls.mantis_node_class_name)
  447. def init(self, context):
  448. super().init(context)
  449. self.use_custom_color = True
  450. self.color = self.category_color
  451. class xFormNode(MantisUINode):
  452. @classmethod
  453. def register(cls):
  454. cls.mantis_class = mantis_class_from_library('.xForm_nodes', cls.mantis_node_class_name)
  455. def init(self, context):
  456. super().init(context)
  457. from mathutils import Color
  458. xFormColor = Color((0.093172, 0.047735, 0.028036)).from_scene_linear_to_srgb()
  459. self.use_custom_color = True
  460. self.color = xFormColor # must not have alpha
  461. class DeformerNode(MantisUINode):
  462. @classmethod
  463. def register(cls):
  464. cls.mantis_class = mantis_class_from_library('.deformer_nodes', cls.mantis_node_class_name)
  465. class GeometryPrimitiveNode(MantisUINode):
  466. @classmethod
  467. def register(cls):
  468. cls.mantis_class = mantis_class_from_library('.primitives_nodes', cls.mantis_node_class_name)
  469. class MantisMiscNode(MantisUINode):
  470. @classmethod
  471. def register(cls):
  472. cls.mantis_class = mantis_class_from_library('.misc_nodes', cls.mantis_node_class_name)
  473. class MantisMathUINode(MantisUINode):
  474. @classmethod
  475. def register(cls):
  476. cls.mantis_class = mantis_class_from_library('.math_nodes', cls.mantis_node_class_name)
  477. def poll_node_tree(self, object):
  478. forbid = []
  479. context = bpy.context
  480. if context.space_data:
  481. if context.space_data.path:
  482. for path_item in context.space_data.path:
  483. forbid.append(path_item.node_tree.name)
  484. if isinstance(object, MantisTree) and object.name not in forbid:
  485. return True
  486. return False
  487. # TODO: try and remove the extra loop used here... but it is OK for now
  488. def should_remove_socket(node, socket):
  489. # a function to check if the socket is in the interface
  490. id_found = False
  491. for item in node.node_tree.interface.items_tree:
  492. if item.item_type != "SOCKET": continue
  493. if item.identifier == socket.identifier:
  494. id_found = True; break
  495. return not id_found
  496. # TODO: try to check identifiers instead of name.
  497. def node_group_update(node, force = False):
  498. if not node.is_updating:
  499. raise RuntimeError("Cannot update node while it is not marked as updating.")
  500. if not force:
  501. if (node.id_data.do_live_update == False) or \
  502. (node.id_data.is_executing == True) or \
  503. (node.id_data.is_exporting == True):
  504. return
  505. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  506. if node.node_tree is None:
  507. node.inputs.clear(); node.outputs.clear()
  508. return
  509. toggle_update = node.id_data.do_live_update
  510. node.id_data.do_live_update = False
  511. identifiers_in={socket.identifier:socket for socket in node.inputs}
  512. identifiers_out={socket.identifier:socket for socket in node.outputs}
  513. interface_names_in, interface_names_out = {}, {}
  514. for interface_item in node.node_tree.interface.items_tree:
  515. if interface_item.item_type != 'SOCKET': continue
  516. if interface_item.in_out == 'INPUT':
  517. interface_names_in[interface_item.identifier] = interface_item.name
  518. else:
  519. interface_names_out[interface_item.identifier] = interface_item.name
  520. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  521. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  522. for i, socket in enumerate(collection):
  523. map[socket.identifier]=i
  524. found_in, found_out = [], []
  525. update_input, update_output = False, False
  526. for item in node.node_tree.interface.items_tree:
  527. if item.item_type != "SOCKET": continue
  528. if item.in_out == 'OUTPUT':
  529. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  530. if interface_names_out.get(item.identifier) != s.name: update_output = True; continue
  531. found_out.append(item.identifier)
  532. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  533. if update_output: continue
  534. if s.bl_idname != item.bl_socket_idname: update_output = True; continue
  535. else: update_output = True; continue
  536. else:
  537. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  538. if interface_names_in.get(item.identifier) != s.name: update_input = True; continue
  539. found_in.append(item.identifier)
  540. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  541. if update_input: continue # done here
  542. if s.bl_idname != item.bl_socket_idname: update_input = True; continue
  543. else: update_input = True; continue
  544. # Schema has an extra input for Length and for Extend.
  545. if node.bl_idname == 'MantisSchemaGroup':
  546. found_in.extend(['Schema Length', ''])
  547. # get the socket maps before modifying stuff
  548. if update_input or update_output:
  549. socket_maps = get_socket_maps(node,)
  550. if socket_maps:
  551. socket_map_in, socket_map_out = socket_maps
  552. if node.bl_idname == "MantisSchemaGroup" and \
  553. len(node.inputs)+len(node.outputs)<=2 and\
  554. len(node.node_tree.interface.items_tree) > 0:
  555. socket_map_in, socket_map_out = None, None
  556. # We have to initialize the node because it only has its base inputs.
  557. elif socket_maps is None:
  558. node.id_data.do_live_update = toggle_update
  559. # if we have too many elements, just get rid of the ones we don't need
  560. if len(node.inputs) > len(found_in):#
  561. for inp in node.inputs:
  562. if inp.identifier in found_in: continue
  563. node.inputs.remove(inp)
  564. if len(node.outputs) > len(found_out):
  565. for out in node.outputs:
  566. if out.identifier in found_out: continue
  567. node.outputs.remove(out)
  568. #
  569. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  570. update_input = True
  571. #
  572. if not (update_input or update_output):
  573. node.id_data.do_live_update = toggle_update
  574. return
  575. # At this point, we know we're gonna change things so let's do this
  576. # remember what has Overlay turned on and what the value is
  577. overlay_state = get_socket_overlay_info(node)
  578. if update_input or update_output and (socket_maps is not None):
  579. if update_input :
  580. if node.bl_idname == 'MantisSchemaGroup':
  581. schema_length=0
  582. if sl := node.inputs.get("Schema Length"):
  583. schema_length = sl.default_value
  584. # sometimes this isn't available yet # TODO not happy about this solution
  585. remove_me=[]
  586. # remove all found map items but the Schema Length input (reuse it)
  587. for i, socket in enumerate(node.inputs):
  588. if socket.identifier == "Schema Length" and i == 0:
  589. continue
  590. elif (socket_map_in is None) or socket.identifier in socket_map_in.keys():
  591. remove_me.append(socket)
  592. elif should_remove_socket(node, socket):
  593. remove_me.append(socket)
  594. while remove_me:
  595. node.inputs.remove(remove_me.pop())
  596. if update_output:
  597. remove_me=[]
  598. for socket in node.outputs:
  599. if (socket_map_out is None) or socket.identifier in socket_map_out.keys():
  600. remove_me.append(socket)
  601. elif should_remove_socket(node, socket):
  602. remove_me.append(socket)
  603. while remove_me:
  604. node.inputs.remove(remove_me.pop())
  605. from .utilities.utilities import relink_socket_map_add_socket
  606. reorder_me_input = []; input_index = 0
  607. reorder_me_output = []; output_index = 0
  608. def update_group_sockets(interface_item, is_input):
  609. socket_map = socket_map_in if is_input else socket_map_out
  610. socket_collection = node.inputs if is_input else node.outputs
  611. counter = input_index if is_input else output_index
  612. reorder_collection = reorder_me_input if is_input else reorder_me_output
  613. socket = None
  614. if socket_map:
  615. if item.identifier in socket_map.keys():
  616. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  617. do_relink(node, socket, socket_map, item.in_out)
  618. else:
  619. for has_socket in socket_collection:
  620. if has_socket.bl_idname == item.bl_socket_idname and \
  621. has_socket.name == item.name:
  622. reorder_collection.append((has_socket, counter))
  623. break
  624. else:
  625. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  626. else:
  627. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  628. counter += 1
  629. # TODO: de-duplicate this hideous stuff
  630. for item in node.node_tree.interface.items_tree:
  631. if item.item_type != "SOCKET": continue
  632. if (item.in_out == 'INPUT' and update_input):
  633. # check and see if it exists... should only happen in curves on startup
  634. if item.bl_socket_idname in ['EnumCurveSocket']:
  635. for exists in node.inputs: # NOTE: check if the socket was not deleted
  636. if exists.identifier == item.identifier:
  637. # this happens for curve inputs because of some shennanigans with how
  638. # blender loads IDs - I can't set the ID until the file has loaded
  639. # so I have to avoid touching the socket until then...
  640. break
  641. else:
  642. update_group_sockets(item, True)
  643. else:
  644. update_group_sockets(item, True)
  645. input_index += 1
  646. if (item.in_out == 'OUTPUT' and update_output):
  647. if item.bl_socket_idname in ['EnumCurveSocket']: # LOOK up there at the comment!
  648. for exists in node.outputs:
  649. if exists.identifier == item.identifier:
  650. break
  651. else:
  652. update_group_sockets(item, False)
  653. else:
  654. update_group_sockets(item, False)
  655. output_index += 1
  656. both_reorders = zip([reorder_me_input, reorder_me_output], [node.inputs, node.outputs])
  657. for reorder_task, collection in both_reorders:
  658. for socket, position in reorder_task:
  659. for i, s in enumerate(collection): # get the index
  660. if s.identifier == socket.identifier: break
  661. else:
  662. prRed(f"WARN: could not reorder socket {socket.name}")
  663. to_index = position
  664. if (not socket.is_output) and node.bl_idname == "MantisSchemaGroup":
  665. to_index+=1
  666. collection.move(i, to_index)
  667. # restore the overlay state, whether it is using Overlay or not and the overlay text
  668. for socket in node.inputs:
  669. if socket and (overlay_text := overlay_state.get(socket.identifier)):
  670. socket.use_overlay=True; socket.overlay_text = overlay_text
  671. # at this point there is no wildcard socket
  672. if socket_map_in and '__extend__' in socket_map_in.keys():
  673. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  674. node.id_data.do_live_update = toggle_update
  675. def node_tree_prop_update(self, context):
  676. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  677. return # so we check if an update is currently running.
  678. self.is_updating = True
  679. def init_schema(self, context):
  680. if len(self.inputs) == 0:
  681. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  682. if self.inputs[-1].bl_idname != "WildcardSocket":
  683. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  684. init_schema(self, context)
  685. try:
  686. node_group_update(self, force=True)
  687. finally: # ensure this line is run even if there is an error
  688. self.is_updating = False
  689. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  690. init_schema(self, context)
  691. from bpy.types import NodeCustomGroup
  692. def group_draw_buttons(self, context, layout):
  693. row = layout.row(align=True)
  694. row.prop(self, "node_tree", text="")
  695. if self.node_tree is None:
  696. row.operator("mantis.new_node_tree", text="", icon='PLUS', emboss=True)
  697. else:
  698. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  699. class MantisNodeGroup(Node, MantisUINode):
  700. bl_idname = "MantisNodeGroup"
  701. bl_label = "Node Group"
  702. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  703. is_updating:BoolProperty(default=False)
  704. def draw_label(self):
  705. if self.node_tree is None:
  706. return "Node Group"
  707. else:
  708. return self.node_tree.name
  709. def draw_buttons(self, context, layout):
  710. group_draw_buttons(self, context, layout)
  711. def update(self):
  712. if self.node_tree is None:
  713. return
  714. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  715. return # so we check if an update is currently running.
  716. live_update = self.id_data.do_live_update
  717. self.is_updating = True
  718. try:
  719. node_group_update(self)
  720. finally: # we need to reset this regardless of whether or not the operation succeeds!
  721. self.is_updating = False
  722. self.id_data.do_live_update = live_update # ensure this remains the same
  723. class GraphError(Exception):
  724. pass
  725. class OverlayApplyError(Exception):
  726. pass
  727. class BlenderVersionError(Exception):
  728. pass
  729. def get_signature_from_edited_tree(node, context):
  730. sig_path=[None,]
  731. for item in context.space_data.path[:-1]:
  732. sig_path.append(item.node_tree.nodes.active.name)
  733. return tuple(sig_path+[node.name])
  734. def poll_node_tree_schema(self, object):
  735. if isinstance(object, SchemaTree):
  736. return True
  737. return False
  738. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  739. class SchemaGroup(Node, MantisUINode):
  740. bl_idname = "MantisSchemaGroup"
  741. bl_label = "Node Schema"
  742. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  743. is_updating:BoolProperty(default=False)
  744. def draw_buttons(self, context, layout):
  745. group_draw_buttons(self, context, layout)
  746. def draw_label(self):
  747. if self.node_tree is None:
  748. return "Schema Group"
  749. else:
  750. return self.node_tree.name
  751. def update(self):
  752. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  753. return # so we check if an update is currently running.
  754. if self.node_tree is None:
  755. return
  756. live_update = self.id_data.do_live_update
  757. self.is_updating = True
  758. try:
  759. node_group_update(self)
  760. # reset things if necessary:
  761. if self.node_tree:
  762. if len(self.inputs) == 0:
  763. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  764. if self.inputs[-1].identifier != "__extend__":
  765. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  766. finally: # we need to reset this regardless of whether or not the operation succeeds!
  767. self.is_updating = False
  768. self.id_data.do_live_update = live_update # ensure this remains the same
  769. # replace names with bl_idnames for reading the tree and solving schemas.
  770. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  771. "SchemaArrayInput", "SchemaArrayInputAll", "SchemaConstInput", "SchemaConstOutput",
  772. "SchemaIndex", "SchemaOutgoingConnection", "SchemaArrayOutput","SchemaArrayInputGet",
  773. ]
  774. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  775. # in schema generation and this is the easiest way to do it for now.
  776. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone",
  777. "xFormArmature", "xFormGeometryObject", "xFormObjectInstance", "xFormCurvePin",]
  778. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  779. from_name_filter = frozenset({"Driver",})
  780. to_name_filter = frozenset({
  781. "Custom Object xForm Override",
  782. "Custom Object",
  783. "Deform Bones",
  784. })
  785. # nodes that must be solved as if they were Schema because they send arrays out.
  786. array_output_types = [
  787. 'UtilityArrayGet', 'UtilityKDChoosePoint', 'UtilityKDChooseXForm',
  788. ]
  789. def can_remove_socket_for_autogen(node, socket) -> bool:
  790. """ Whether to enable socket removal optimization for the socket
  791. This should be disallowed if e.g. it is a custom property.
  792. """
  793. return False # for now! This doesn't seem to be working...
  794. # the problem is that Schema does this, and so does Readtree
  795. # and they can try and both do it. That's bad.
  796. if node.socket_templates:
  797. for s_template in node.socket_templates:
  798. if s_template.name == socket:
  799. # raise NotImplementedError
  800. return True
  801. elif node.node_type == 'UTILITY':
  802. return True # HACK because most utilities don't have socket templates yet
  803. return False
  804. # The MantisExecutionContext class is used to store the execution-specific variables
  805. # that are used when executing the tree
  806. # Importantly, it is NOT used to store variables between solutions, these belong to the
  807. # tree class.
  808. class MantisExecutionContext():
  809. def __init__(
  810. self,
  811. base_tree,
  812. ):
  813. self.base_tree = base_tree
  814. self.execution_id = base_tree.execution_id
  815. self.execution_failed=False
  816. self.interface_nodes = {}
  817. self.b_objects={} # objects created by Mantis during execution
  818. self.tagged_for_overlay = [] # nodes mutated by overlay system
  819. self.overlay_data = [] # dict of list of Overlay objects
  820. from typing import Any
  821. # using these frozen sets accelerate lookup when checking for this
  822. FILL_PARAMETERS_SKIP_ROOTS = frozenset({ 'MANTIS_AUTOGENERATED', 'SCHEMA_AUTOGENERATED', })
  823. FILL_PARAMETERS_SKIP_NAMES = frozenset({ "NodeGroupOutput", "NodeGroupInput", })
  824. FILL_PARAMETERS_SKIP_SOCKETS = frozenset({ 'RelationshipSocket', 'xFormSocket', })
  825. from .socket_definitions import no_default_value
  826. class MantisNode:
  827. """
  828. This class contains the basic interface for a Mantis Node.
  829. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  830. It gets generated with data from a MantisUINode when the graph is read.
  831. """
  832. __slots__ = (
  833. "base_tree", "signature", "ui_signature",
  834. "inputs", "outputs",
  835. "parameters", "drivers", "bObject",
  836. "hierarchy_connections", "connections",
  837. "hierarchy_dependencies", "dependencies",
  838. "unmet_hierarchy_dependency_count",
  839. "prepared", "executed", "execution_prepared",
  840. "mContext", "is_schema_prototype",
  841. "generated_at_schema_index",
  842. )
  843. node_type = 'UNINITIALIZED'
  844. socket_templates = None
  845. property_socket_map = {}
  846. passes=frozenset({})
  847. def __init__(self, signature : tuple,
  848. base_tree : bpy.types.NodeTree,
  849. socket_templates : list[MantisSocketTemplate]=[],
  850. additional_parameters :dict = {}, ):
  851. self.base_tree=base_tree
  852. self.signature = signature
  853. self.ui_signature = signature
  854. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  855. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  856. self.parameters, self.drivers = {}, []; self.bObject=None
  857. self.hierarchy_connections, self.connections = [], []
  858. self.hierarchy_dependencies, self.dependencies = [], []
  859. self.unmet_hierarchy_dependency_count = float("inf") # we will set this when filling the dependencies lists
  860. self.prepared, self.executed = False, False
  861. self.execution_prepared = False
  862. # execution_prepared is for tracking prep state in execution, so that I can avoid preparing nodes
  863. # again without changing the readtree code much.
  864. self.mContext = None # for now I am gonna set this at runtime
  865. self.is_schema_prototype = False
  866. # For nodes generated in a schema, it's a list so that we can store the whole path
  867. # this is not strictly necessary for interface resolution but it is much easier
  868. # initialize it as all -1, we'll modify this if we need to, e.g. in the schema
  869. self.generated_at_schema_index = [-1] * len(self.signature)
  870. # I know it isn't "beautiful OOP" or whatever, but it is just easier
  871. # code should be simple and do things in the simplest way.
  872. # in the future I can refactor it, but it will require changes to 100+
  873. # classes, instead of adding about 5 lines of code elsewhere.
  874. if self.socket_templates:
  875. self.init_sockets( additional_parameters )
  876. @property
  877. def name(self):
  878. return self.ui_signature[-1]
  879. @property
  880. def bl_idname(self): # this and the above exist solely to maintain interface w/bpy.types.Node
  881. from .utilities.utilities import get_ui_node
  882. return get_ui_node(self.ui_signature, self.base_tree).bl_idname
  883. def reset_execution(self) -> None:
  884. """ Reset the node for additional execution without re-building the tree."""
  885. self.drivers.clear(); self.bObject=None
  886. self.executed = False
  887. self.execution_prepared = False
  888. def init_sockets(self, additional_parameters : dict = {}) -> None:
  889. # Formerly I was doing this:
  890. # self.inputs.init_sockets(self.socket_templates)
  891. # self.outputs.init_sockets(self.socket_templates)
  892. # Since doing each one causes some redundancy, we'll just reimplement it
  893. # This is a highly used and therefore expensive function so we have to make small
  894. # optimizations like this, even tho it is ugly.
  895. traverse_in, traverse_out = {}, {}
  896. for socket in self.socket_templates:
  897. if socket.traverse_target:
  898. if socket.is_input:
  899. traverse_in[socket.name] = socket.traverse_target
  900. else:
  901. traverse_out[socket.name] = socket.traverse_target
  902. if socket.ui_only == True: continue # used in UI but not in generation
  903. if socket.is_input:
  904. self.inputs[socket.name] = NodeSocket(is_input=True, name=socket.name,
  905. node=self, socket_type=socket.bl_idname)
  906. else:
  907. self.outputs[socket.name] = NodeSocket(is_input=False, name=socket.name,
  908. node=self, socket_type=socket.bl_idname)
  909. self.parameters[socket.name] = None
  910. for traverse_owner, traverse_target in traverse_in.items():
  911. self.inputs[traverse_owner].traverse_target = self.outputs[traverse_target]
  912. self.inputs[traverse_owner].can_traverse = True
  913. for traverse_owner, traverse_target in traverse_out.items():
  914. self.outputs[traverse_owner].traverse_target = self.inputs[traverse_target]
  915. self.outputs[traverse_owner].can_traverse = True
  916. for key, value in additional_parameters.items():
  917. self.parameters[key]=value
  918. def init_parameters(self, additional_parameters = {}) -> None:
  919. for socket in self.inputs:
  920. self.parameters[socket.name] = None
  921. for socket in self.outputs:
  922. self.parameters[socket.name] = None
  923. for key, value in additional_parameters.items():
  924. self.parameters[key]=value
  925. # We really only need to do this once at class registration
  926. # Therefore the goal is not to have any mutable data here
  927. # ======================= READ BELOW =======================
  928. # We have the following classes of Mantis Socket ==> Blender Proeprty relationships:
  929. # Scalar: 1 Mantis scalar ==> 1 Blender property. 1 Filler.
  930. # Vector: 1 Mantis Vector socket ==> Blender vector property. 1 Filler.
  931. # Scalar Combo: 1 Mantis scalar ==> many Blender scalars. 1 Filler per property.
  932. # Vector Combo: 1 Mantis vector ==> vector of Blender vector property. 1 Filler per property.
  933. # In every case, 1 filler per Blender property.
  934. @classmethod
  935. def gen_property_socket_map(cls, prop_owner_group=None) -> dict:
  936. from .mantis_dataclasses import MantisSocketFiller
  937. from dataclasses import replace
  938. from bpy.app import version as bpy_version
  939. if cls.property_socket_map: # retrieve the cache if possible
  940. return cls.property_socket_map
  941. props_sockets = {}
  942. for s_template in cls.socket_templates:
  943. if s_template.min_bpy_version:
  944. if bpy_version < s_template.min_bpy_version:
  945. prPurple(f"Skipping socket {s_template.name} because "
  946. f"it requires Blender {s_template.min_bpy_version} or higher")
  947. continue # We can't set or drive this obviously.
  948. if prop_owner_group is not None and s_template.prop_owner_group != prop_owner_group:
  949. continue # for composite objects like bones
  950. if not s_template.blender_property: # this one has to be handled by the node itself.
  951. continue # Or maybe it is UI-only, in any case we don't need to do anything here.
  952. # Default to (Scalar <==> Scalar), as tuples for compatibility with other code paths
  953. vector_property, combo = False, False # TODO: make socket templates pre-tuple-ize this
  954. defaults = ( s_template.default_value, ); properties = ( s_template.blender_property, )
  955. if isinstance( s_template.default_value, (list, tuple) ):
  956. vector_property = True # this tells us if MANTIS provides a vector
  957. # if Blender consumes a vector, then we map the vector to the vector. Easy.
  958. if isinstance(s_template.blender_property, (tuple, list)):
  959. # But maybe we provide data from one Mantis Socket to many Blender properties...
  960. combo=True; properties = s_template.blender_property
  961. if vector_property: # we have to break the default value up so we can map
  962. # mantis data element-wise to a vector of Blender properties
  963. defaults = s_template.default_value
  964. # Now iteratre through the properties and make 1 filler per.
  965. for i, property in enumerate(properties):
  966. default_index = i if vector_property and combo else 0 # only needed for Combo Vector
  967. default = defaults[default_index] # usually 1:1 except for Combo Scalar
  968. key = s_template.name + f"_{default_index}" + (f"_{property}" if combo else "")
  969. value_index = default_index if combo and vector_property else None
  970. from .utilities import socket_filler_operators as operators
  971. property_value_operator = None
  972. if s_template.property_value_operator:
  973. property_value_operator = getattr(operators, s_template.property_value_operator)
  974. props_sockets[key] = MantisSocketFiller(
  975. socket_name = s_template.name, # This is a dict because node
  976. property_name = property, # instances should be able
  977. value_index = value_index, # to edit Fillers.
  978. default_value = default, # The keys are not inherently
  979. combo_property = combo, # meaningful and are
  980. vector_property = vector_property, # NOT USED DOWNSTREAM!
  981. is_animatable = s_template.is_animatable,
  982. property_group = s_template.prop_owner_group,
  983. property_value_operator = property_value_operator)
  984. if prop_owner_group is None:
  985. cls.property_socket_map = props_sockets # We should cache this one!
  986. return props_sockets
  987. def set_traverse(self, traversal_pairs = [(str, str)]) -> None:
  988. for (a, b) in traversal_pairs:
  989. self.inputs[a].set_traverse_target(self.outputs[b])
  990. self.outputs[b].set_traverse_target(self.inputs[a])
  991. def clear_traverse(self, inputs = [str], outputs = [str]) -> None:
  992. for inp in inputs:
  993. self.inputs[inp].set_traverse(None)
  994. for out in outputs:
  995. self.inputs[out].set_traverse(None)
  996. def flush_links(self) -> None:
  997. for inp in self.inputs.values():
  998. inp.flush_links()
  999. for out in self.outputs.values():
  1000. out.flush_links()
  1001. def update_socket_value(self, blender_property, value) -> bool:
  1002. change_handled=False
  1003. if self.node_type == 'LINK':
  1004. if len(self.bObject) == 0: # - there are no downstream xForms
  1005. return True # so there is nothing to do here
  1006. for b_ob in self.bObject:
  1007. try:
  1008. setattr(b_ob, blender_property, value)
  1009. change_handled=True
  1010. except Exception as e:
  1011. print("Failed to update mantis socket because of %s" % e,
  1012. "Updating tree instead.")
  1013. else:
  1014. try:
  1015. b_ob = self.bObject
  1016. if self.node_type == 'XFORM': # HACK
  1017. b_ob = self.bGetObject()
  1018. setattr(b_ob, blender_property, value)
  1019. change_handled=True
  1020. except Exception as e:
  1021. print("Failed to update mantis socket because of %s" % e,
  1022. "Updating tree instead.")
  1023. return change_handled
  1024. def ui_modify_socket(self, ui_socket, socket_name=None) -> bool:
  1025. from .execution.overlays import ( node_scan_overlays, get_socket_idname_data_type,
  1026. parser_handle_text, handle_overlay_detect )
  1027. """ Handle changes in the node's UI. Updates the rig if possible."""
  1028. # Always update the node's data
  1029. change_handled=False
  1030. if socket_name is None: socket_name = ui_socket.name
  1031. value = ui_socket.default_value
  1032. if hasattr(ui_socket, 'use_overlay') and ui_socket.use_overlay:
  1033. value = ui_socket.overlay_text
  1034. if get_socket_idname_data_type(ui_socket.bl_idname) != str:
  1035. value = parser_handle_text(value)
  1036. # apply overlay variables here so this updates predictably
  1037. if (isinstance(value, str) and
  1038. (self.signature, ui_socket.identifier) in self.mContext.tagged_for_overlay):
  1039. try:
  1040. value = node_scan_overlays(self, ui_socket.identifier)
  1041. except OverlayApplyError:
  1042. return False # failed to apply the overlay and handle the change
  1043. # TODO: I need to make Node Groups apply overlays downstream, but since
  1044. # they don't update live anyway, no need just yet
  1045. if socket_name == 'Enable': value = not value
  1046. try:
  1047. self.parameters[ui_socket.name]=value
  1048. except KeyError:
  1049. prRed(f"Unhandled change occured in socket {ui_socket.name} in node"
  1050. f" {ui_socket.node.name} in tree {ui_socket.node.id_data.name}.")
  1051. for s_template in self.socket_templates:
  1052. if s_template.name==ui_socket.name:
  1053. change_handled = True
  1054. if not s_template.blender_property: return False
  1055. elif isinstance(s_template.blender_property, str):
  1056. change_handled &= self.update_socket_value(
  1057. s_template.blender_property, value)
  1058. else: # it is a tuple
  1059. for i, prop in enumerate(s_template.blender_property):
  1060. try:
  1061. change_handled &= self.update_socket_value(
  1062. prop, value[i])
  1063. except IndexError:
  1064. prRed(f"{ui_socket.name} does not have enough values to unpack"
  1065. " to update the Mantis tree. Please report this as a bug.")
  1066. change_handled=False
  1067. break # we don't have to look through any more socket templates
  1068. return change_handled
  1069. # the goal here is to tag the node as unprepared
  1070. # but some nodes are always prepared, so we have to kick it forward.
  1071. def reset_execution_recursive(self):
  1072. self.reset_execution()
  1073. if self.prepared==False: return # all good from here
  1074. for conn in self.hierarchy_connections:
  1075. conn.reset_execution_recursive()
  1076. def evaluate_input(self, input_name, index=0) -> Any:
  1077. from .utilities.node_common import trace_single_line
  1078. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  1079. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  1080. # this trace() should give a key error if there is a problem
  1081. # it is NOT handled here because it should NOT happen - so I want the error message.
  1082. trace = trace_single_line(self, input_name, index)
  1083. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  1084. return prop
  1085. def fill_parameters(self, ui_node=None) -> None:
  1086. from mathutils import Matrix
  1087. from .execution.overlays import handle_overlay_detect, get_socket_idname_data_type, parser_handle_text
  1088. if not ui_node:
  1089. if ( (self.signature[0] in FILL_PARAMETERS_SKIP_ROOTS) or
  1090. (self.signature[-1] in FILL_PARAMETERS_SKIP_NAMES) ): # I think this is harmless
  1091. return None
  1092. raise RuntimeError(wrapRed("No UI Node found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  1093. ui_inputs = ui_node.inputs; ui_outputs = ui_node.outputs
  1094. for key in self.parameters.keys():
  1095. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  1096. continue # will be filled by the node itself
  1097. if node_socket := ui_inputs.get(key):
  1098. if node_socket.bl_idname in FILL_PARAMETERS_SKIP_SOCKETS: continue
  1099. elif node_socket.is_linked and (not node_socket.is_output): continue
  1100. # we will get the value from the link, because this is a linked input port.
  1101. # very importantly, we do not pass linked outputs
  1102. # fill these because they are probably Input nodes.
  1103. if node_socket.bl_idname in no_default_value: continue
  1104. if node_socket.bl_idname == 'MatrixSocket':
  1105. v = node_socket.default_value
  1106. self.parameters[key] = Matrix(( tuple(v[0:4]),
  1107. tuple(v[4:8]),
  1108. tuple(v[8:12]),
  1109. tuple(v[12:16]) ))
  1110. elif (value := node_socket.default_value) is not None:
  1111. if hasattr(node_socket, 'use_overlay') and node_socket.use_overlay:
  1112. value = node_socket.overlay_text
  1113. if get_socket_idname_data_type(node_socket.bl_idname) != str:
  1114. value = parser_handle_text(value)
  1115. # TODO: the overlay system should use a math parser for numerical types
  1116. # that treats strings as variable names
  1117. # but for now I am just gonna hamfist it like this lol
  1118. if isinstance(value, str) and "$" in value:
  1119. value = handle_overlay_detect(self,
  1120. node_socket.identifier, node_socket.bl_idname, value)
  1121. self.parameters[key] = value
  1122. else:
  1123. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  1124. # I don't think this works! but I like the idea
  1125. def call_on_all_ancestors(self, *args, **kwargs):
  1126. """Resolve the dependencies of this node with the named method and its arguments.
  1127. First, dependencies are discovered by walking backwards through the tree. Once the root
  1128. nodes are discovered, the method is called by each node in dependency order.
  1129. The first argument MUST be the name of the method as a string.
  1130. """
  1131. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  1132. from .utilities.utilities import get_all_dependencies
  1133. from collections import deque
  1134. # get all dependencies by walking backward through the tree.
  1135. all_dependencies = get_all_dependencies(self)
  1136. # get just the roots
  1137. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  1138. solved = set()
  1139. while can_solve:
  1140. node = can_solve.pop()
  1141. method = getattr(node, args[0])
  1142. method(*args[0:], **kwargs)
  1143. solved.add(node)
  1144. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  1145. if self in solved:
  1146. break
  1147. return
  1148. # gets targets for constraints and deformers and should handle all cases
  1149. def get_target_and_subtarget(self, constraint_or_deformer, input_name = "Target", index = 0,):
  1150. from bpy.types import PoseBone, Object, SplineIKConstraint
  1151. subtarget = ''; target = self.evaluate_input(input_name, index)
  1152. if target:
  1153. if not hasattr(target, "bGetObject"):
  1154. if hasattr(constraint_or_deformer, 'name'):
  1155. name = constraint_or_deformer.name
  1156. else:
  1157. name = 'NAME NOT FOUND'
  1158. prRed(f"No {input_name} target found for {name} in {self} because there is no connected node, or node is wrong type")
  1159. return
  1160. if (isinstance(target.bGetObject(), PoseBone)):
  1161. subtarget = target.bGetObject().name
  1162. target = target.bGetParentArmature()
  1163. elif (isinstance(target.bGetObject(), Object) ):
  1164. target = target.bGetObject()
  1165. else:
  1166. raise RuntimeError("Cannot interpret constraint or deformer target!")
  1167. if (isinstance(constraint_or_deformer, SplineIKConstraint)):
  1168. if target and target.type not in ["CURVE"]:
  1169. raise GraphError(wrapRed("Error: %s requires a Curve input, not %s" %
  1170. (self, type(target))))
  1171. constraint_or_deformer.target = target# don't get a subtarget
  1172. if (input_name == 'Pole Target'):
  1173. constraint_or_deformer.pole_target, constraint_or_deformer.pole_subtarget = target, subtarget
  1174. else:
  1175. if hasattr(constraint_or_deformer, "target"):
  1176. constraint_or_deformer.target = target
  1177. if hasattr(constraint_or_deformer, "object"):
  1178. constraint_or_deformer.object = target
  1179. if hasattr(constraint_or_deformer, "subtarget"):
  1180. constraint_or_deformer.subtarget = subtarget
  1181. # This function is for registering the objects a node creates in the global dict
  1182. # The goal is to have a global map of node <==> object and object <==> node
  1183. # so that we can do e.g. selection syncing, etc.
  1184. # NOTE: I'm not registering with mContext here, that happens elsewhere
  1185. # but it is probably a good idea to refactor this together.
  1186. def bRegisterObject(self, ob_type, ob_value, sub_ob_value = None):
  1187. ui_signature = self.ui_signature
  1188. if selection_sync_node_to_object.get(ui_signature) is None:
  1189. selection_sync_node_to_object[ui_signature] = []
  1190. ob_name = ob_value.name
  1191. sub_ob_name = sub_ob_value.name if sub_ob_value else None
  1192. key = (ob_name, sub_ob_name)
  1193. if ob_type in ['OBJECT', 'BONE']:
  1194. selection_sync_object_to_node[key] = ui_signature
  1195. selection_sync_node_to_object[ui_signature].append( key )
  1196. # PASSES DEFINED HERE!
  1197. def bPrepare(self, bContext=None):
  1198. return # This one runs BEFORE anything else
  1199. def bTransformPass(self, bContext=None):
  1200. return # This one runs in EDIT MODE
  1201. def bRelationshipPass(self, bContext=None):
  1202. return # This one runs in POSE MODE
  1203. def bFinalize(self, bContext=None):
  1204. return
  1205. def bModifierApply(self, bContext=None):
  1206. return
  1207. if environ.get("DOERROR"):
  1208. def __repr__(self):
  1209. return self.signature.__repr__()
  1210. else:
  1211. def __repr__(self):
  1212. return self.ui_signature.__repr__()
  1213. # do I need this and the link class above?
  1214. class DummyLink:
  1215. __slots__ = ("from_socket", "to_socket",
  1216. "from_mantis_node", "to_mantis_node",
  1217. "multi_input_sort_id",
  1218. "original_from")
  1219. #gonna use this for faking links to keep the interface consistent
  1220. def __init__(self, from_socket, to_socket, from_mantis_node=None, to_mantis_node=None, original_from=None, multi_input_sort_id=0):
  1221. self.from_socket = from_socket
  1222. self.to_socket = to_socket
  1223. self.from_mantis_node = from_mantis_node
  1224. self.to_mantis_node = to_mantis_node
  1225. self.multi_input_sort_id = multi_input_sort_id
  1226. # self.from_node = from_socket.node
  1227. # self.to_node = to_socket.node
  1228. if (original_from):
  1229. self.original_from = original_from
  1230. else:
  1231. self.original_from = self.from_socket
  1232. def __repr__(self):
  1233. return(self.from_mantis_node.__repr__()+":"+self.from_socket.name + " -> " + self.to_mantis_node.__repr__()+":"+self.to_socket.name)
  1234. def detect_hierarchy_link(from_node, from_socket, to_node, to_socket,):
  1235. if to_node.node_type in ['DUMMY_SCHEMA', 'SCHEMA']:
  1236. return False #TODO: find out if filtering SCHEMA types is wise
  1237. if from_socket in from_name_filter and to_socket in {"Array"}:
  1238. # SPECIAL CASE: arrays essentially extend the non-hierarchy edge
  1239. # so if the connection to the array isn't hierarchy, the array node
  1240. # in the middle gets disconnected and never executes.
  1241. # SO we need to make all the edges until the end hierarchy.
  1242. # TODO: test the graph for cycles and tag the "last" edge in the cycle
  1243. # is the general solution but that is toooooo slow in Python
  1244. return True
  1245. if (from_socket in from_name_filter) or (to_socket in to_name_filter):
  1246. return False
  1247. # if from_node.__class__.__name__ in ["UtilityCombineVector", "UtilityCombineThreeBool"]:
  1248. # return False
  1249. return True
  1250. class NodeLink:
  1251. __slots__ = (
  1252. "from_node",
  1253. "from_socket",
  1254. "to_node",
  1255. "to_socket",
  1256. "multi_input_sort_id",
  1257. "sub_sort_id",
  1258. "is_hierarchy",
  1259. "is_alive",
  1260. )
  1261. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0, sub_sort_id=0):
  1262. if from_node.signature == to_node.signature:
  1263. raise RuntimeError("Cannot connect a node to itself.")
  1264. self.from_node = from_node
  1265. self.from_socket = from_socket
  1266. self.to_node = to_node
  1267. self.to_socket = to_socket
  1268. self.from_node.outputs[self.from_socket].links.append(self)
  1269. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  1270. self.multi_input_sort_id = multi_input_sort_id # this is the sort_id of the link in the UI
  1271. self.sub_sort_id = sub_sort_id # this is for sorting within a bundled link (one link in the UI)
  1272. self.to_node.inputs[self.to_socket].links.append(self)
  1273. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  1274. self.is_alive = True
  1275. def __repr__(self):
  1276. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  1277. # link_string = # if I need to colorize output for debugging.
  1278. # if self.is_hierarchy:
  1279. # return wrapOrange(link_string)
  1280. # else:
  1281. # return wrapWhite(link_string)
  1282. def die(self):
  1283. self.is_alive = False
  1284. self.to_node.inputs[self.to_socket].flush_links()
  1285. self.from_node.outputs[self.from_socket].flush_links()
  1286. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  1287. to_node = self.to_node
  1288. to_socket = self.to_socket
  1289. self.to_node = middle_node
  1290. self.to_socket = middle_node_in
  1291. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  1292. if re_init_hierarchy:
  1293. from .utilities.utilities import init_connections, init_dependencies
  1294. init_connections(self.from_node)
  1295. init_connections(middle_node)
  1296. init_dependencies(middle_node)
  1297. init_dependencies(to_node)
  1298. class NodeSocket:
  1299. __slots__ = (
  1300. "can_traverse",
  1301. "traverse_target",
  1302. "node",
  1303. "name",
  1304. "is_input",
  1305. "links",
  1306. "is_linked",
  1307. "socket_type",
  1308. )
  1309. def __init__(self, is_input = False,
  1310. node = None, name = None,
  1311. traverse_target = None,
  1312. socket_type=""):
  1313. self.can_traverse = False # to/from the other side of the parent node
  1314. self.traverse_target = None
  1315. self.node = node
  1316. self.name = name
  1317. self.is_input = is_input
  1318. self.links = []
  1319. self.is_linked = False
  1320. self.socket_type = socket_type
  1321. if (traverse_target):
  1322. self.can_traverse = True
  1323. def connect(self, node, socket, sort_id=0, sub_sort_id=0):
  1324. if (self.is_input):
  1325. to_node = self.node; from_node = node
  1326. to_socket = self.name; from_socket = socket
  1327. else:
  1328. from_node = self.node; to_node = node
  1329. from_socket = self.name; to_socket = socket
  1330. from_node.outputs[from_socket].is_linked = True
  1331. to_node.inputs[to_socket].is_linked = True
  1332. # NOTE: I have removed a check for duplicate links here.
  1333. # Schemas sometimes have valid duplicate links.
  1334. # It is conceivable that this will lead to bugs, but I judge it unlikely.
  1335. new_link = NodeLink(
  1336. from_node,
  1337. from_socket,
  1338. to_node,
  1339. to_socket,
  1340. sort_id,
  1341. sub_sort_id)
  1342. return new_link
  1343. def set_traverse_target(self, traverse_target):
  1344. self.traverse_target = traverse_target
  1345. if traverse_target: self.can_traverse = True
  1346. else: self.can_traverse = False
  1347. def flush_links(self):
  1348. """ Removes dead links from this socket."""
  1349. self.links = [l for l in self.links if l.is_alive]
  1350. self.links.sort(key=links_sort_key)
  1351. self.is_linked = bool(self.links)
  1352. @property
  1353. def is_connected(self):
  1354. return len(self.links)>0
  1355. def __repr__(self):
  1356. return self.node.__repr__() + "::" + self.name
  1357. class MantisNodeSocketCollection(dict):
  1358. __slots__ = ("is_input", "node",)
  1359. def __init__(self, node, is_input=False):
  1360. self.is_input = is_input
  1361. self.node = node
  1362. def init_sockets(self, sockets):
  1363. for socket in sockets:
  1364. if socket.ui_only == True: continue # used in UI but not in generation
  1365. if socket.is_input != self.is_input: continue
  1366. self[socket.name] = NodeSocket(is_input=self.is_input, name=socket.name, node=self.node)
  1367. def __delitem__(self, key):
  1368. """Deletes a node socket by name, and all its links."""
  1369. socket = self[key]
  1370. for l in socket.links:
  1371. l.die()
  1372. super().__delitem__(key)
  1373. def __iter__(self):
  1374. """Makes the class iterable"""
  1375. return iter(self.values())