VFXView.cs 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873
  1. using System;
  2. using System.Collections;
  3. using System.Collections.ObjectModel;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using UnityEditor.Experimental.GraphView;
  9. using UnityEditor.Toolbars;
  10. using UnityEditor.VersionControl;
  11. using UnityEngine;
  12. using UnityEngine.VFX;
  13. using UnityEngine.UIElements;
  14. using UnityEditor.UIElements;
  15. using UnityEngine.Profiling;
  16. using PositionType = UnityEngine.UIElements.Position;
  17. using Task = UnityEditor.VersionControl.Task;
  18. namespace UnityEditor.VFX.UI
  19. {
  20. /// <summary>
  21. /// Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor.
  22. /// </summary>
  23. [Obsolete("Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor")]
  24. public class VFXViewModicationProcessor : UnityEditor.AssetModificationProcessor
  25. {
  26. /// <summary>
  27. /// Initialized to false by default.
  28. /// Obsolete API : Use a custom UnityEditor.AssetModificationProcessor and implement OnWillMoveAsset if you relied on this behavior.
  29. /// </summary>
  30. public static bool assetMoved = false;
  31. }
  32. class VFXViewModificationProcessor : UnityEditor.AssetModificationProcessor
  33. {
  34. public static bool assetMoved = false;
  35. private static AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
  36. {
  37. assetMoved = true;
  38. return AssetMoveResult.DidNotMove;
  39. }
  40. }
  41. class EdgeDragInfo : VisualElement
  42. {
  43. VFXView m_View;
  44. public EdgeDragInfo(VFXView view)
  45. {
  46. m_View = view;
  47. var tpl = Resources.Load<VisualTreeAsset>("uxml/EdgeDragInfo");
  48. tpl.CloneTree(this);
  49. this.AddStyleSheetPath("EdgeDragInfo");
  50. m_Text = this.Q<Label>("title");
  51. pickingMode = PickingMode.Ignore;
  52. m_Text.pickingMode = PickingMode.Ignore;
  53. }
  54. Label m_Text;
  55. public void StartEdgeDragInfo(VFXDataAnchor draggedAnchor, VFXDataAnchor overAnchor)
  56. {
  57. string error = null;
  58. if (draggedAnchor != overAnchor)
  59. {
  60. if (draggedAnchor.direction == overAnchor.direction)
  61. {
  62. if (draggedAnchor.direction == Direction.Input)
  63. error = "You must link an input to an output";
  64. else
  65. error = "You must link an output to an input";
  66. }
  67. else if (draggedAnchor.controller.connections.Any(t => draggedAnchor.direction == Direction.Input ? t.output == overAnchor.controller : t.input == overAnchor.controller))
  68. {
  69. error = "An edge with the same input and output already exists";
  70. }
  71. else if (!draggedAnchor.controller.model.CanLink(overAnchor.controller.model))
  72. {
  73. error = "The input and output have incompatible types";
  74. }
  75. else
  76. {
  77. bool can = draggedAnchor.controller.CanLink(overAnchor.controller);
  78. if (!can)
  79. {
  80. if (!draggedAnchor.controller.CanLinkToNode(overAnchor.controller.sourceNode, null))
  81. error = "The edge would create a loop in the operators";
  82. else
  83. error = "Link impossible for an unknown reason";
  84. }
  85. }
  86. }
  87. if (error == null)
  88. style.display = DisplayStyle.None;
  89. else
  90. m_Text.text = error;
  91. var layout = overAnchor.connector.parent.ChangeCoordinatesTo(m_View, overAnchor.connector.layout);
  92. style.top = layout.yMax + 16;
  93. style.left = layout.xMax;
  94. }
  95. }
  96. struct VFXViewSettings
  97. {
  98. private bool m_IsAttachedLocked;
  99. private VisualEffect m_AttachedVisualEffect;
  100. public void Load(bool force = false)
  101. {
  102. m_IsAttachedLocked = EditorPrefs.GetBool(nameof(m_IsAttachedLocked));
  103. if (EditorApplication.isPlaying || force)
  104. {
  105. var attachedVisualEffectPath = EditorPrefs.GetString(nameof(m_AttachedVisualEffect));
  106. if (!string.IsNullOrEmpty(attachedVisualEffectPath))
  107. {
  108. var go = GameObject.Find(attachedVisualEffectPath);
  109. if (go != null)
  110. {
  111. m_AttachedVisualEffect = go.GetComponent<VisualEffect>();
  112. }
  113. }
  114. }
  115. }
  116. public VisualEffect AttachedVisualEffect
  117. {
  118. get => m_AttachedVisualEffect;
  119. set
  120. {
  121. m_AttachedVisualEffect = value;
  122. if (!EditorApplication.isPlaying)
  123. {
  124. if (m_AttachedVisualEffect != null)
  125. {
  126. var go = m_AttachedVisualEffect.gameObject;
  127. var path = go.GetComponentsInParent<UnityEngine.Transform>()
  128. .Select(x => x.name)
  129. .Reverse()
  130. .ToArray();
  131. EditorPrefs.SetString(nameof(m_AttachedVisualEffect), "/" + string.Join('/', path));
  132. }
  133. else
  134. {
  135. EditorPrefs.SetString(nameof(m_AttachedVisualEffect), null);
  136. }
  137. }
  138. }
  139. }
  140. public bool AttachedLocked
  141. {
  142. get => m_IsAttachedLocked;
  143. set
  144. {
  145. m_IsAttachedLocked = value;
  146. EditorPrefs.SetBool(nameof(m_IsAttachedLocked), m_IsAttachedLocked);
  147. }
  148. }
  149. }
  150. class VFXView : GraphView, IControlledElement<VFXViewController>, IControllerListener, IDisposable
  151. {
  152. private const int MaximumNameLengthInNotification = 128;
  153. internal static class Contents
  154. {
  155. public static readonly GUIContent attach = EditorGUIUtility.TrTextContent("Attach");
  156. public static readonly GUIContent detach = EditorGUIUtility.TrTextContent("Detach");
  157. public static readonly GUIContent clickToUnlock = EditorGUIUtility.TrTextContent("Click to enable auto-attachment to selection");
  158. public static readonly GUIContent clickToLock = EditorGUIUtility.TrTextContent("Click to disable auto-attachment to selection");
  159. public static readonly GUIContent noSelection = EditorGUIUtility.TrTextContent("No selection");
  160. public static readonly GUIContent attachedToGameObject = EditorGUIUtility.TrTextContent("Attached to {0}");
  161. public static readonly GUIContent notAttached = EditorGUIUtility.TrTextContent("Select a Game Object running this VFX to attach it");
  162. }
  163. public HashSet<VFXEditableDataAnchor> allDataAnchors = new HashSet<VFXEditableDataAnchor>();
  164. public bool locked => m_VFXSettings.AttachedLocked;
  165. void IControllerListener.OnControllerEvent(ControllerEvent e)
  166. {
  167. if (e is VFXRecompileEvent)
  168. {
  169. var recompileEvent = e as VFXRecompileEvent;
  170. foreach (var anchor in allDataAnchors)
  171. {
  172. anchor.OnRecompile(recompileEvent.valueOnly);
  173. }
  174. }
  175. }
  176. VFXViewSettings m_VFXSettings;
  177. VisualElement m_NoAssetLabel;
  178. VisualElement m_LockedElement;
  179. VFXViewController m_Controller;
  180. Controller IControlledElement.controller
  181. {
  182. get { return m_Controller; }
  183. }
  184. public Button checkoutButton;
  185. void DisconnectController()
  186. {
  187. if (controller.model && controller.graph)
  188. controller.graph.SetCompilationMode(VFXViewPreference.forceEditionCompilation ? VFXCompilationMode.Edition : VFXCompilationMode.Runtime);
  189. m_Controller.UnregisterHandler(this);
  190. m_Controller.useCount--;
  191. serializeGraphElements = null;
  192. unserializeAndPaste = null;
  193. deleteSelection = null;
  194. nodeCreationRequest = null;
  195. elementsAddedToGroup = null;
  196. elementsRemovedFromGroup = null;
  197. groupTitleChanged = null;
  198. m_GeometrySet = false;
  199. // Remove all in view now that the controller has been disconnected.
  200. foreach (var element in rootGroupNodeElements.Values)
  201. {
  202. RemoveElement(element);
  203. }
  204. foreach (var element in groupNodes.Values)
  205. {
  206. RemoveElement(element);
  207. }
  208. foreach (var element in dataEdges.Values)
  209. {
  210. RemoveElement(element);
  211. }
  212. foreach (var element in flowEdges.Values)
  213. {
  214. RemoveElement(element);
  215. }
  216. foreach (var system in m_Systems)
  217. {
  218. RemoveElement(system);
  219. }
  220. groupNodes.Clear();
  221. stickyNotes.Clear();
  222. rootNodes.Clear();
  223. rootGroupNodeElements.Clear();
  224. m_Systems.Clear();
  225. VFXExpression.ClearCache();
  226. m_NodeProvider = null;
  227. if (m_Controller.graph)
  228. {
  229. m_Controller.graph.errorManager.onClearAllErrors -= ClearAllErrors;
  230. m_Controller.graph.errorManager.onRegisterError -= RegisterError;
  231. }
  232. }
  233. void ConnectController()
  234. {
  235. schedule.Execute(() =>
  236. {
  237. if (controller != null && controller.graph)
  238. controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
  239. }).ExecuteLater(1);
  240. if (m_Controller.graph)
  241. {
  242. m_Controller.graph.errorManager.onClearAllErrors += ClearAllErrors;
  243. m_Controller.graph.errorManager.onRegisterError += RegisterError;
  244. }
  245. m_Controller.RegisterHandler(this);
  246. m_Controller.useCount++;
  247. serializeGraphElements = SerializeElements;
  248. unserializeAndPaste = UnserializeAndPasteElements;
  249. deleteSelection = Delete;
  250. nodeCreationRequest = OnCreateNode;
  251. elementsAddedToGroup = ElementAddedToGroupNode;
  252. elementsRemovedFromGroup = ElementRemovedFromGroupNode;
  253. groupTitleChanged = GroupNodeTitleChanged;
  254. m_NodeProvider = new VFXNodeProvider(controller, (d, mPos) => AddNode(d, mPos), null, GetAcceptedTypeNodes());
  255. //Make sure a subgraph block as a block subgraph context
  256. if (controller.model.isSubgraph && controller.model.subgraph is VisualEffectSubgraphBlock)
  257. {
  258. if (!controller.graph.children.Any(t => t is VFXBlockSubgraphContext))
  259. {
  260. controller.graph.AddChild(VFXBlockSubgraphContext.CreateInstance<VFXBlockSubgraphContext>(), 0);
  261. }
  262. }
  263. }
  264. IEnumerable<Type> GetAcceptedTypeNodes()
  265. {
  266. if (!controller.model.isSubgraph)
  267. return null;
  268. return new Type[] { typeof(VFXOperator) };
  269. }
  270. public VisualEffect attachedComponent
  271. {
  272. get
  273. {
  274. return m_ComponentBoard.GetAttachedComponent();
  275. }
  276. set
  277. {
  278. if (value == null)
  279. m_ComponentBoard.Detach();
  280. else
  281. m_ComponentBoard.Attach(value);
  282. }
  283. }
  284. public void RemoveAnchorEdges(VFXDataAnchor anchor)
  285. {
  286. foreach (var edge in dataEdges.Where(t => t.Value.input == anchor || t.Value.output == anchor).ToArray())
  287. {
  288. if (edge.Value.input == anchor)
  289. edge.Value.output.Disconnect(edge.Value);
  290. else
  291. edge.Value.input.Disconnect(edge.Value);
  292. RemoveElement(edge.Value);
  293. dataEdges.Remove(edge.Key);
  294. }
  295. }
  296. public void RemoveNodeEdges(VFXNodeUI node)
  297. {
  298. foreach (var edge in dataEdges.Where(t => t.Value.input.node == node || t.Value.output.node == node).ToArray())
  299. {
  300. RemoveElement(edge.Value);
  301. dataEdges.Remove(edge.Key);
  302. }
  303. }
  304. public VFXViewController controller
  305. {
  306. get { return m_Controller; }
  307. set
  308. {
  309. if (m_Controller != value)
  310. {
  311. if (m_Controller != null)
  312. {
  313. DisconnectController();
  314. }
  315. m_Controller = value;
  316. if (m_Controller != null)
  317. {
  318. ConnectController();
  319. }
  320. NewControllerSet();
  321. AttachToSelection();
  322. m_ComponentBoard.ResetPlayRate();
  323. }
  324. }
  325. }
  326. public VFXGroupNode GetPickedGroupNode(Vector2 panelPosition)
  327. {
  328. List<VisualElement> picked = new List<VisualElement>();
  329. panel.PickAll(panelPosition, picked);
  330. return picked.OfType<VFXGroupNode>().FirstOrDefault();
  331. }
  332. public VFXNodeController AddNode(VFXNodeProvider.Descriptor d, Vector2 mPos)
  333. {
  334. UpdateSelectionWithNewNode();
  335. var groupNode = GetPickedGroupNode(mPos);
  336. mPos = this.ChangeCoordinatesTo(contentViewContainer, mPos);
  337. if (d.modelDescriptor is string)
  338. {
  339. string path = d.modelDescriptor as string;
  340. if (path.StartsWith(VisualEffectAssetEditorUtility.templatePath) || ((VFXResources.defaultResources.userTemplateDirectory.Length > 0) && path.StartsWith(VFXResources.defaultResources.userTemplateDirectory)))
  341. CreateTemplateSystem(path, mPos, groupNode);
  342. else
  343. {
  344. if (Path.GetExtension(path) == VisualEffectSubgraphOperator.Extension)
  345. {
  346. var subGraph = AssetDatabase.LoadAssetAtPath<VisualEffectSubgraphOperator>(path);
  347. if (subGraph != null && (!controller.model.isSubgraph || !subGraph.GetResource().GetOrCreateGraph().subgraphDependencies.Contains(controller.model.subgraph) && subGraph.GetResource() != controller.model))
  348. {
  349. ;
  350. VFXModel newModel = VFXSubgraphOperator.CreateInstance<VFXSubgraphOperator>() as VFXModel;
  351. controller.AddVFXModel(mPos, newModel);
  352. newModel.SetSettingValue("m_Subgraph", subGraph);
  353. UpdateSelectionWithNewNode();
  354. controller.LightApplyChanges();
  355. return controller.GetNewNodeController(newModel);
  356. }
  357. }
  358. }
  359. }
  360. else if (d.modelDescriptor is GroupNodeAdder)
  361. {
  362. controller.AddGroupNode(mPos);
  363. }
  364. else if (d.modelDescriptor is VFXParameterController)
  365. {
  366. var parameter = d.modelDescriptor as VFXParameterController;
  367. UpdateSelectionWithNewNode();
  368. return controller.AddVFXParameter(mPos, parameter, groupNode != null ? groupNode.controller : null);
  369. }
  370. else
  371. {
  372. UpdateSelectionWithNewNode();
  373. return controller.AddNode(mPos, d.modelDescriptor, groupNode != null ? groupNode.controller : null);
  374. }
  375. return null;
  376. }
  377. readonly VisualElement m_Toolbar;
  378. readonly ToolbarToggle m_LockToggle;
  379. readonly EditorToolbarDropdown m_AttachDropDownButton;
  380. VFXNodeProvider m_NodeProvider;
  381. ToolbarButton m_SaveButton;
  382. bool m_IsRuntimeMode;
  383. bool m_ForceShaderValidation;
  384. public static StyleSheet LoadStyleSheet(string text)
  385. {
  386. string path = string.Format("{0}/uss/{1}.uss", VisualEffectAssetEditorUtility.editorResourcesPath, text);
  387. return AssetDatabase.LoadAssetAtPath<StyleSheet>(path);
  388. }
  389. public static VisualTreeAsset LoadUXML(string text)
  390. {
  391. string path = string.Format("{0}/uxml/{1}.uxml", VisualEffectAssetEditorUtility.editorResourcesPath, text);
  392. return AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(path);
  393. }
  394. public static Texture2D LoadImage(string text)
  395. {
  396. string path = string.Format("{0}/VFX/{1}.png", VisualEffectAssetEditorUtility.editorResourcesPath, text);
  397. return AssetDatabase.LoadAssetAtPath<Texture2D>(path);
  398. }
  399. SelectionDragger m_SelectionDragger;
  400. RectangleSelector m_RectangleSelector;
  401. public void OnCreateAsset()
  402. {
  403. string filePath = EditorUtility.SaveFilePanelInProject("", "New Graph", "vfx", "Create new VisualEffect Graph");
  404. if (!string.IsNullOrEmpty(filePath))
  405. {
  406. VisualEffectAssetEditorUtility.CreateTemplateAsset(filePath);
  407. VFXViewWindow.currentWindow.LoadAsset(AssetDatabase.LoadAssetAtPath<VisualEffectAsset>(filePath), null);
  408. }
  409. }
  410. public VFXView()
  411. {
  412. EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
  413. SetupZoom(0.125f, 8);
  414. this.AddManipulator(new ContentDragger());
  415. m_SelectionDragger = new SelectionDragger();
  416. m_RectangleSelector = new RectangleSelector();
  417. this.AddManipulator(m_SelectionDragger);
  418. this.AddManipulator(m_RectangleSelector);
  419. this.AddManipulator(new FreehandSelector());
  420. styleSheets.Add(LoadStyleSheet("VFXView"));
  421. if (!EditorGUIUtility.isProSkin)
  422. {
  423. styleSheets.Add(LoadStyleSheet("VFXView-light"));
  424. }
  425. else
  426. {
  427. styleSheets.Add(LoadStyleSheet("VFXView-dark"));
  428. }
  429. AddLayer(-1);
  430. AddLayer(1);
  431. AddLayer(2);
  432. focusable = true;
  433. m_Toolbar = new UnityEditor.UIElements.Toolbar();
  434. var toggleAutoCompile = new ToolbarToggle();
  435. toggleAutoCompile.text = "Auto";
  436. toggleAutoCompile.style.unityTextAlign = TextAnchor.MiddleRight;
  437. toggleAutoCompile.SetValueWithoutNotify(true);
  438. toggleAutoCompile.RegisterCallback<ChangeEvent<bool>>(OnToggleCompile);
  439. m_Toolbar.Add(toggleAutoCompile);
  440. var compileButton = new ToolbarButton(OnCompile);
  441. compileButton.style.unityTextAlign = TextAnchor.MiddleLeft;
  442. compileButton.text = "Compile";
  443. m_Toolbar.Add(compileButton);
  444. var resyncMatButton = new ToolbarButton(OnResyncMaterial);
  445. resyncMatButton.style.unityTextAlign = TextAnchor.MiddleLeft;
  446. resyncMatButton.text = "Resync Material";
  447. m_Toolbar.Add(resyncMatButton);
  448. m_SaveButton = new ToolbarButton(OnSave);
  449. m_SaveButton.style.unityTextAlign = TextAnchor.MiddleLeft;
  450. m_SaveButton.text = "Save";
  451. m_Toolbar.Add(m_SaveButton);
  452. m_AttachDropDownButton = new EditorToolbarDropdown(Contents.attach.text, OnOpenAttachMenu);
  453. m_AttachDropDownButton.name = "attach-toolbar-button";
  454. m_Toolbar.Add(m_AttachDropDownButton);
  455. m_LockToggle = new ToolbarToggle();
  456. m_LockToggle.style.unityTextAlign = TextAnchor.MiddleLeft;
  457. m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
  458. m_LockToggle.name = "lock-auto-attach";
  459. m_LockToggle.RegisterCallback<ChangeEvent<bool>>(OnToggleLock);
  460. m_Toolbar.Add(m_LockToggle);
  461. var spacer = new ToolbarSpacer();
  462. spacer.style.width = 12f;
  463. m_Toolbar.Add(spacer);
  464. var selectAssetButton = new ToolbarButton(() => { SelectAsset(); });
  465. selectAssetButton.text = "Show in Project";
  466. m_Toolbar.Add(selectAssetButton);
  467. spacer = new ToolbarSpacer();
  468. spacer.style.width = 10;
  469. m_Toolbar.Add(spacer);
  470. checkoutButton = new ToolbarButton(() => { Checkout(); });
  471. checkoutButton.text = "Check Out";
  472. checkoutButton.visible = false;
  473. checkoutButton.AddToClassList("toolbarItem");
  474. m_Toolbar.Add(checkoutButton);
  475. var flexSpacer = new ToolbarSpacer();
  476. flexSpacer.style.flexGrow = 1f;
  477. m_Toolbar.Add(flexSpacer);
  478. var toggleBlackboard = new ToolbarToggle();
  479. toggleBlackboard.text = "Blackboard";
  480. toggleBlackboard.RegisterCallback<ChangeEvent<bool>>(ToggleBlackboard);
  481. m_Toolbar.Add(toggleBlackboard);
  482. m_ToggleComponentBoard = new ToolbarToggle();
  483. m_ToggleComponentBoard.text = "Control";
  484. m_ToggleComponentBoard.RegisterCallback<ChangeEvent<bool>>(ToggleComponentBoard);
  485. m_Toolbar.Add(m_ToggleComponentBoard);
  486. var showDebugMenu = new ToolbarMenu();
  487. showDebugMenu.text = "Advanced";
  488. showDebugMenu.menu.AppendAction("Runtime Mode (Forced)", OnRuntimeModeChanged, RuntimeModeStatus);
  489. showDebugMenu.menu.AppendAction("Shader Validation (Forced)", OnShaderValidationChanged, ShaderValidationStatus);
  490. showDebugMenu.menu.AppendSeparator();
  491. showDebugMenu.menu.AppendAction("Refresh UI", OnRefreshUI, DropdownMenuAction.Status.Normal);
  492. m_Toolbar.Add(showDebugMenu);
  493. // End Toolbar
  494. m_NoAssetLabel = new Label("\n\n\nTo begin creating Visual Effects, create a new Visual Effect Graph Asset.\n(or double-click an existing Visual Effect Graph in the project view)") { name = "no-asset" };
  495. m_NoAssetLabel.style.position = PositionType.Absolute;
  496. m_NoAssetLabel.style.left = new StyleLength(40f);
  497. m_NoAssetLabel.style.right = new StyleLength(40f);
  498. m_NoAssetLabel.style.top = new StyleLength(40f);
  499. m_NoAssetLabel.style.bottom = new StyleLength(140f);
  500. m_NoAssetLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
  501. m_NoAssetLabel.style.fontSize = new StyleLength(12f);
  502. m_NoAssetLabel.style.color = Color.white * 0.75f;
  503. Add(m_NoAssetLabel);
  504. var createButton = new Button() { text = "Create new Visual Effect Graph" };
  505. m_NoAssetLabel.Add(createButton);
  506. createButton.clicked += OnCreateAsset;
  507. m_LockedElement = new Label("Asset is Locked");
  508. m_LockedElement.style.position = PositionType.Absolute;
  509. m_LockedElement.style.left = 0f;
  510. m_LockedElement.style.right = new StyleLength(0f);
  511. m_LockedElement.style.top = new StyleLength(0f);
  512. m_LockedElement.style.bottom = new StyleLength(0f);
  513. m_LockedElement.style.unityTextAlign = TextAnchor.MiddleCenter;
  514. m_LockedElement.style.fontSize = new StyleLength(72f);
  515. m_LockedElement.style.color = Color.white * 0.75f;
  516. m_LockedElement.style.display = DisplayStyle.None;
  517. m_LockedElement.focusable = true;
  518. m_LockedElement.RegisterCallback<KeyDownEvent>(e => e.StopPropagation());
  519. m_Blackboard = new VFXBlackboard(this);
  520. bool blackboardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.blackboard, true);
  521. if (blackboardVisible)
  522. Add(m_Blackboard);
  523. toggleBlackboard.value = blackboardVisible;
  524. m_ComponentBoard = new VFXComponentBoard(this);
  525. #if _ENABLE_RESTORE_BOARD_VISIBILITY
  526. bool componentBoardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.componentBoard, false);
  527. if (componentBoardVisible)
  528. ShowComponentBoard();
  529. toggleComponentBoard.value = componentBoardVisible;
  530. #endif
  531. Add(m_LockedElement);
  532. Add(m_Toolbar);
  533. m_Toolbar.SetEnabled(false);
  534. m_VFXSettings = new VFXViewSettings();
  535. m_VFXSettings.Load();
  536. m_LockToggle.value = m_VFXSettings.AttachedLocked;
  537. RegisterCallback<DragUpdatedEvent>(OnDragUpdated);
  538. RegisterCallback<DragPerformEvent>(OnDragPerform);
  539. RegisterCallback<ValidateCommandEvent>(ValidateCommand);
  540. RegisterCallback<ExecuteCommandEvent>(ExecuteCommand);
  541. RegisterCallback<AttachToPanelEvent>(OnEnterPanel);
  542. RegisterCallback<DetachFromPanelEvent>(OnLeavePanel);
  543. RegisterCallback<KeyDownEvent>(OnKeyDownEvent);
  544. graphViewChanged = VFXGraphViewChanged;
  545. elementResized = VFXElementResized;
  546. canPasteSerializedData = VFXCanPaste;
  547. viewDataKey = "VFXView";
  548. RegisterCallback<GeometryChangedEvent>(OnFirstResize);
  549. }
  550. public void Dispose()
  551. {
  552. UnregisterCallback<DragUpdatedEvent>(OnDragUpdated);
  553. UnregisterCallback<DragPerformEvent>(OnDragPerform);
  554. UnregisterCallback<ValidateCommandEvent>(ValidateCommand);
  555. UnregisterCallback<ExecuteCommandEvent>(ExecuteCommand);
  556. UnregisterCallback<AttachToPanelEvent>(OnEnterPanel);
  557. UnregisterCallback<DetachFromPanelEvent>(OnLeavePanel);
  558. UnregisterCallback<KeyDownEvent>(OnKeyDownEvent);
  559. UnregisterCallback<GeometryChangedEvent>(OnFirstResize);
  560. EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
  561. }
  562. void OnPlayModeStateChanged(PlayModeStateChange playModeState)
  563. {
  564. if (playModeState == PlayModeStateChange.EnteredEditMode)
  565. {
  566. m_VFXSettings.Load(true);
  567. TryAttachTo(m_VFXSettings.AttachedVisualEffect);
  568. }
  569. }
  570. void OnOpenAttachMenu()
  571. {
  572. var attachPanel = ScriptableObject.CreateInstance<VFXAttachPanel>();
  573. var bounds = new Rect(ViewToScreenPosition(m_AttachDropDownButton.worldBound.position), m_AttachDropDownButton.worldBound.size);
  574. bounds.xMin++;
  575. attachPanel.ShowAsDropDown(bounds, attachPanel.WindowSize, new[] { PopupLocation.BelowAlignLeft });
  576. }
  577. void OnRefreshUI(DropdownMenuAction action)
  578. {
  579. Resync();
  580. }
  581. void OnRuntimeModeChanged(DropdownMenuAction action)
  582. {
  583. m_IsRuntimeMode = !m_IsRuntimeMode;
  584. controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
  585. }
  586. DropdownMenuAction.Status RuntimeModeStatus(DropdownMenuAction action)
  587. {
  588. if (m_IsRuntimeMode)
  589. return DropdownMenuAction.Status.Checked;
  590. else
  591. return DropdownMenuAction.Status.Normal;
  592. }
  593. void OnShaderValidationChanged(DropdownMenuAction action)
  594. {
  595. m_ForceShaderValidation = !m_ForceShaderValidation;
  596. controller.graph.SetForceShaderValidation(m_ForceShaderValidation);
  597. }
  598. DropdownMenuAction.Status ShaderValidationStatus(DropdownMenuAction action)
  599. {
  600. if (m_ForceShaderValidation)
  601. return DropdownMenuAction.Status.Checked;
  602. else
  603. return DropdownMenuAction.Status.Normal;
  604. }
  605. [NonSerialized]
  606. Dictionary<VFXModel, List<IconBadge>> m_InvalidateBadges = new Dictionary<VFXModel, List<IconBadge>>();
  607. [NonSerialized]
  608. List<IconBadge> m_CompileBadges = new List<IconBadge>();
  609. private void RegisterError(VFXModel model, VFXErrorOrigin errorOrigin, string error, VFXErrorType type, string description)
  610. {
  611. VisualElement target = null;
  612. VisualElement targetParent = null;
  613. SpriteAlignment alignement = SpriteAlignment.TopLeft;
  614. if (model is VFXSlot)
  615. {
  616. var slot = (VFXSlot)model;
  617. // todo manage parameter slot if they can have error
  618. var nodeController = controller.GetNodeController(slot.owner as VFXModel, 0);
  619. if (nodeController == null)
  620. return;
  621. var anchorController = (slot.direction == VFXSlot.Direction.kInput ? nodeController.inputPorts : nodeController.outputPorts).FirstOrDefault(t => t.model == slot);
  622. if (anchorController == null)
  623. return;
  624. targetParent = GetNodeByController(nodeController);
  625. target = (targetParent as VFXNodeUI).GetPorts(slot.direction == VFXSlot.Direction.kInput, slot.direction != VFXSlot.Direction.kInput).FirstOrDefault(t => t.controller == anchorController);
  626. alignement = slot.direction == VFXSlot.Direction.kInput ? SpriteAlignment.LeftCenter : SpriteAlignment.RightCenter;
  627. }
  628. else if (model is IVFXSlotContainer)
  629. {
  630. var node = model;
  631. var nodeController = controller.GetNodeController(node, 0);
  632. if (nodeController == null)
  633. return;
  634. target = GetNodeByController(nodeController);
  635. if (target == null)
  636. return;
  637. if (nodeController is VFXBlockController blkController)
  638. {
  639. VFXNodeUI targetContext = GetNodeByController(blkController.contextController);
  640. if (targetContext == null)
  641. return;
  642. targetParent = targetContext.parent;
  643. }
  644. else
  645. {
  646. targetParent = target.parent;
  647. }
  648. target = (target as VFXNodeUI).titleContainer;
  649. alignement = SpriteAlignment.LeftCenter;
  650. }
  651. if (target != null && targetParent != null)
  652. {
  653. var badge = type == VFXErrorType.Error ? IconBadge.CreateError(description) : IconBadge.CreateComment(description);
  654. targetParent.Add(badge);
  655. badge.AttachTo(target, alignement);
  656. if (errorOrigin == VFXErrorOrigin.Compilation)
  657. {
  658. m_CompileBadges.Add(badge);
  659. }
  660. else
  661. {
  662. List<IconBadge> badges;
  663. if (!m_InvalidateBadges.TryGetValue(model, out badges))
  664. {
  665. badges = new List<IconBadge>();
  666. m_InvalidateBadges[model] = badges;
  667. }
  668. badges.Add(badge);
  669. }
  670. badge.AddManipulator(new Clickable(() =>
  671. {
  672. badge.Detach();
  673. badge.RemoveFromHierarchy();
  674. }));
  675. badge.AddManipulator(new DownClickable(() =>
  676. {
  677. GenericMenu menu = new GenericMenu();
  678. menu.AddItem(EditorGUIUtility.TrTextContent("Hide"), false, () =>
  679. {
  680. badge.Detach();
  681. badge.RemoveFromHierarchy();
  682. });
  683. if (type != VFXErrorType.Error)
  684. {
  685. menu.AddItem(EditorGUIUtility.TrTextContent("Ignore"), false, () =>
  686. {
  687. badge.Detach();
  688. badge.RemoveFromHierarchy();
  689. model.IgnoreError(error);
  690. });
  691. }
  692. menu.ShowAsContext();
  693. }
  694. ));
  695. }
  696. }
  697. private void ClearAllErrors(VFXModel model, VFXErrorOrigin errorOrigin)
  698. {
  699. if (errorOrigin == VFXErrorOrigin.Compilation)
  700. {
  701. foreach (var badge in m_CompileBadges)
  702. {
  703. badge.Detach();
  704. badge.RemoveFromHierarchy();
  705. }
  706. m_CompileBadges.Clear();
  707. }
  708. else
  709. {
  710. if (!object.ReferenceEquals(model, null))
  711. {
  712. List<IconBadge> badges;
  713. if (m_InvalidateBadges.TryGetValue(model, out badges))
  714. {
  715. foreach (var badge in badges)
  716. {
  717. badge.Detach();
  718. badge.RemoveFromHierarchy();
  719. }
  720. m_InvalidateBadges.Remove(model);
  721. }
  722. }
  723. else
  724. throw new InvalidOperationException("Can't clear in Invalidate mode without a model");
  725. }
  726. }
  727. public void SetBoardToFront(GraphElement board)
  728. {
  729. board.SendToBack();
  730. board.PlaceBehind(m_Toolbar);
  731. }
  732. public void AttachToSelection()
  733. {
  734. var vfxWindow = VFXViewWindow.currentWindow;
  735. if (TryAttachTo((Selection.activeObject as GameObject)?.GetComponent<VisualEffect>()) && vfxWindow != null)
  736. {
  737. string truncatedObjectName = TruncateName(Selection.activeObject.name, MaximumNameLengthInNotification);
  738. vfxWindow.ShowNotification(new GUIContent($"Attached to {truncatedObjectName}"), 1.5);
  739. vfxWindow.Repaint();
  740. }
  741. }
  742. public bool TryAttachTo(VisualEffect selectedAsset)
  743. {
  744. bool attached = false;
  745. if (selectedAsset != null && controller?.graph.visualEffectResource.asset == selectedAsset.visualEffectAsset)
  746. {
  747. attached = m_ComponentBoard.Attach(selectedAsset);
  748. }
  749. m_VFXSettings.AttachedVisualEffect = attached ? selectedAsset : null;
  750. UpdateToolbarButtons();
  751. return attached;
  752. }
  753. internal void Detach()
  754. {
  755. m_ComponentBoard.Detach();
  756. UpdateToolbarButtons();
  757. }
  758. public void DetachIfDeleted()
  759. {
  760. if (m_ComponentBoard.GetAttachedComponent() == null)
  761. {
  762. Detach();
  763. }
  764. }
  765. private void UpdateToolbarButtons()
  766. {
  767. if (attachedComponent != null)
  768. {
  769. m_AttachDropDownButton.AddToClassList("checked");
  770. }
  771. else
  772. {
  773. m_AttachDropDownButton.RemoveFromClassList("checked");
  774. }
  775. m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
  776. m_AttachDropDownButton.tooltip = attachedComponent != null && !string.IsNullOrEmpty(attachedComponent.name)
  777. ? string.Format(Contents.attachedToGameObject.text, TruncateName(attachedComponent.name, MaximumNameLengthInNotification))
  778. : Contents.notAttached.text;
  779. }
  780. string TruncateName(string nameToTruncate, int maxLength)
  781. {
  782. return nameToTruncate.Length > maxLength
  783. ? nameToTruncate.Substring(0, maxLength) + "..."
  784. : nameToTruncate;
  785. }
  786. void OnUndoPerformed()
  787. {
  788. foreach (var anchor in allDataAnchors)
  789. {
  790. anchor.ForceUpdate();
  791. }
  792. this.m_Blackboard.ForceUpdate();
  793. }
  794. void OnToggleLock(ChangeEvent<bool> evt)
  795. {
  796. m_VFXSettings.AttachedLocked = !locked;
  797. if (!locked)
  798. {
  799. AttachToSelection();
  800. }
  801. else
  802. {
  803. UpdateToolbarButtons();
  804. }
  805. }
  806. void ToggleBlackboard(ChangeEvent<bool> e)
  807. {
  808. if (m_Blackboard.parent == null)
  809. {
  810. Insert(childCount - 1, m_Blackboard);
  811. BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.blackboard, true);
  812. m_Blackboard.RegisterCallback<GeometryChangedEvent>(OnFirstBlackboardGeometryChanged);
  813. m_Blackboard.style.position = PositionType.Absolute;
  814. }
  815. else
  816. {
  817. m_Blackboard.RemoveFromHierarchy();
  818. BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.blackboard, false);
  819. }
  820. }
  821. void ToggleComponentBoard()
  822. {
  823. if (m_ComponentBoard.parent == null)
  824. {
  825. Insert(childCount - 1, m_ComponentBoard);
  826. BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.componentBoard, true);
  827. m_ComponentBoard.RegisterCallback<GeometryChangedEvent>(OnFirstComponentBoardGeometryChanged);
  828. }
  829. else
  830. {
  831. m_ComponentBoard.RemoveFromHierarchy();
  832. BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.componentBoard, false);
  833. }
  834. m_ComponentBoard.RefreshInitializeErrors();
  835. }
  836. void OnFirstComponentBoardGeometryChanged(GeometryChangedEvent e)
  837. {
  838. if (m_FirstResize)
  839. {
  840. m_ComponentBoard.ValidatePosition();
  841. m_ComponentBoard.UnregisterCallback<GeometryChangedEvent>(OnFirstComponentBoardGeometryChanged);
  842. }
  843. }
  844. void OnFirstBlackboardGeometryChanged(GeometryChangedEvent e)
  845. {
  846. if (m_FirstResize)
  847. {
  848. m_Blackboard.ValidatePosition();
  849. m_Blackboard.UnregisterCallback<GeometryChangedEvent>(OnFirstBlackboardGeometryChanged);
  850. }
  851. }
  852. public bool m_FirstResize = false;
  853. void OnFirstResize(GeometryChangedEvent e)
  854. {
  855. m_FirstResize = true;
  856. m_ComponentBoard.ValidatePosition();
  857. m_Blackboard.ValidatePosition();
  858. UnregisterCallback<GeometryChangedEvent>(OnFirstResize);
  859. }
  860. Toggle m_ToggleComponentBoard;
  861. void ToggleComponentBoard(ChangeEvent<bool> e)
  862. {
  863. ToggleComponentBoard();
  864. }
  865. public void OnVisualEffectComponentChanged(IEnumerable<VisualEffect> visualEffects)
  866. {
  867. m_ComponentBoard.OnVisualEffectComponentChanged(visualEffects);
  868. }
  869. void Delete(string cmd, AskUser askUser)
  870. {
  871. var currentSelection = selection.ToArray();
  872. var parametersToRemove = Enumerable.Empty<VFXParameterController>();
  873. foreach (var category in currentSelection.OfType<VFXBlackboardCategory>())
  874. {
  875. parametersToRemove = parametersToRemove.Concat(controller.RemoveCategory(m_Blackboard.GetCategoryIndex(category)));
  876. }
  877. controller.Remove(currentSelection.OfType<IControlledElement>().Select(t => t.controller).Concat(parametersToRemove.Cast<Controller>()), true);
  878. }
  879. void IControlledElement.OnControllerChanged(ref ControllerChangedEvent e)
  880. {
  881. if (e.controller == controller)
  882. {
  883. ControllerChanged(e.change);
  884. }
  885. else if (e.controller is VFXNodeController)
  886. {
  887. UpdateUIBounds();
  888. if (e.controller is VFXContextController && e.target is VFXContextUI)
  889. {
  890. m_ComponentBoard.UpdateEventList();
  891. UpdateSystemNames();
  892. }
  893. }
  894. }
  895. bool m_InControllerChanged;
  896. void ControllerChanged(int change)
  897. {
  898. if (change == VFXViewController.Change.assetName)
  899. return;
  900. m_InControllerChanged = true;
  901. if (change == VFXViewController.Change.groupNode)
  902. {
  903. Profiler.BeginSample("VFXView.SyncGroupNodes");
  904. SyncGroupNodes();
  905. Profiler.EndSample();
  906. var groupNodes = this.groupNodes;
  907. foreach (var groupNode in groupNodes.Values)
  908. {
  909. Profiler.BeginSample("VFXGroupNode.SelfChange");
  910. groupNode.SelfChange();
  911. Profiler.EndSample();
  912. }
  913. return;
  914. }
  915. if (change == VFXViewController.Change.destroy)
  916. {
  917. m_Blackboard.controller = null;
  918. controller = null;
  919. return;
  920. }
  921. Profiler.BeginSample("VFXView.ControllerChanged");
  922. if (change == VFXViewController.AnyThing)
  923. {
  924. SyncNodes();
  925. }
  926. Profiler.BeginSample("VFXView.SyncStickyNotes");
  927. SyncStickyNotes();
  928. Profiler.EndSample();
  929. Profiler.BeginSample("VFXView.SyncEdges");
  930. SyncEdges(change);
  931. Profiler.EndSample();
  932. Profiler.BeginSample("VFXView.SyncGroupNodes");
  933. SyncGroupNodes();
  934. Profiler.EndSample();
  935. if (controller != null)
  936. {
  937. if (change == VFXViewController.AnyThing)
  938. {
  939. // if the asset is destroyed somehow, fox example if the user delete the asset, update the controller and update the window.
  940. var asset = controller.model;
  941. if (asset == null)
  942. {
  943. this.controller = null;
  944. return;
  945. }
  946. }
  947. }
  948. m_InControllerChanged = false;
  949. if (change != VFXViewController.Change.dataEdge)
  950. UpdateSystems();
  951. if (m_UpdateUIBounds)
  952. {
  953. Profiler.BeginSample("VFXView.UpdateUIBounds");
  954. UpdateUIBounds();
  955. Profiler.EndSample();
  956. }
  957. Profiler.EndSample();
  958. }
  959. public bool IsAssetEditable()
  960. {
  961. return controller.model != null && controller.model.IsAssetEditable();
  962. }
  963. void NewControllerSet()
  964. {
  965. m_Blackboard.controller = controller;
  966. m_ComponentBoard.controller = controller;
  967. if (controller != null)
  968. {
  969. m_NoAssetLabel.RemoveFromHierarchy();
  970. m_Toolbar.SetEnabled(true);
  971. m_AttachDropDownButton.SetEnabled(this.controller.graph.visualEffectResource.subgraph == null);
  972. m_LockToggle.SetEnabled(this.controller.graph.visualEffectResource.subgraph == null);
  973. if (IsAssetEditable())
  974. {
  975. m_LockedElement.style.display = DisplayStyle.None;
  976. m_Blackboard.UnlockUI();
  977. }
  978. else
  979. {
  980. m_LockedElement.style.display = DisplayStyle.Flex;
  981. m_Blackboard.LockUI();
  982. }
  983. }
  984. else
  985. {
  986. if (m_NoAssetLabel.parent == null)
  987. {
  988. Add(m_NoAssetLabel);
  989. m_Toolbar.SetEnabled(false);
  990. }
  991. }
  992. if (m_VFXSettings.AttachedVisualEffect != null)
  993. {
  994. TryAttachTo(m_VFXSettings.AttachedVisualEffect);
  995. }
  996. }
  997. public void OnFocus()
  998. {
  999. if (controller != null && controller.model.asset != null && !IsAssetEditable())
  1000. {
  1001. if (m_LockedElement.style.display != DisplayStyle.Flex)
  1002. {
  1003. m_LockedElement.style.display = DisplayStyle.Flex;
  1004. this.RemoveManipulator(m_SelectionDragger);
  1005. this.RemoveManipulator(m_RectangleSelector);
  1006. m_LockedElement.Focus();
  1007. }
  1008. m_Blackboard.LockUI();
  1009. }
  1010. else
  1011. {
  1012. if (m_LockedElement.style.display != DisplayStyle.None)
  1013. {
  1014. m_LockedElement.style.display = DisplayStyle.None;
  1015. this.AddManipulator(m_SelectionDragger);
  1016. this.AddManipulator(m_RectangleSelector);
  1017. }
  1018. m_Blackboard.UnlockUI();
  1019. }
  1020. if (m_Blackboard.parent != null)
  1021. m_LockedElement.PlaceInFront(contentViewContainer);
  1022. }
  1023. public void FrameNewController()
  1024. {
  1025. if (panel != null)
  1026. {
  1027. FrameAfterAWhile();
  1028. }
  1029. else
  1030. {
  1031. RegisterCallback<GeometryChangedEvent>(OnFrameNewControllerWithPanel);
  1032. }
  1033. }
  1034. void FrameAfterAWhile()
  1035. {
  1036. var rectToFit = contentViewContainer.layout;
  1037. var frameTranslation = Vector3.zero;
  1038. var frameScaling = Vector3.one;
  1039. rectToFit = controller.graph.UIInfos.uiBounds;
  1040. if (rectToFit.width <= 50 || rectToFit.height <= 50)
  1041. {
  1042. return;
  1043. }
  1044. Rect rectAvailable = layout;
  1045. float validateFloat = rectAvailable.x + rectAvailable.y + rectAvailable.width + rectAvailable.height;
  1046. if (float.IsInfinity(validateFloat) || float.IsNaN(validateFloat))
  1047. {
  1048. schedule.Execute(FrameAfterAWhile);
  1049. return;
  1050. }
  1051. CalculateFrameTransform(rectToFit, rectAvailable, 30, out frameTranslation, out frameScaling);
  1052. Matrix4x4.TRS(frameTranslation, Quaternion.identity, frameScaling);
  1053. UpdateViewTransform(frameTranslation, frameScaling);
  1054. contentViewContainer.MarkDirtyRepaint();
  1055. }
  1056. bool m_GeometrySet = false;
  1057. void OnFrameNewControllerWithPanel(GeometryChangedEvent e)
  1058. {
  1059. m_GeometrySet = true;
  1060. FrameAfterAWhile();
  1061. UnregisterCallback<GeometryChangedEvent>(OnFrameNewControllerWithPanel);
  1062. }
  1063. Dictionary<VFXNodeController, VFXNodeUI> rootNodes = new Dictionary<VFXNodeController, VFXNodeUI>();
  1064. Dictionary<Controller, GraphElement> rootGroupNodeElements = new Dictionary<Controller, GraphElement>();
  1065. public GraphElement GetGroupNodeElement(Controller controller)
  1066. {
  1067. GraphElement result = null;
  1068. rootGroupNodeElements.TryGetValue(controller, out result);
  1069. return result;
  1070. }
  1071. Dictionary<VFXGroupNodeController, VFXGroupNode> groupNodes = new Dictionary<VFXGroupNodeController, VFXGroupNode>();
  1072. Dictionary<VFXStickyNoteController, VFXStickyNote> stickyNotes = new Dictionary<VFXStickyNoteController, VFXStickyNote>();
  1073. void OnOneNodeGeometryChanged(GeometryChangedEvent e)
  1074. {
  1075. m_GeometrySet = true;
  1076. (e.target as GraphElement).UnregisterCallback<GeometryChangedEvent>(OnOneNodeGeometryChanged);
  1077. }
  1078. bool m_UpdateSelectionWithNewNode;
  1079. public void UpdateSelectionWithNewNode()
  1080. {
  1081. m_UpdateSelectionWithNewNode = true;
  1082. }
  1083. void SyncNodes()
  1084. {
  1085. Profiler.BeginSample("VFXView.SyncNodes");
  1086. if (controller == null)
  1087. {
  1088. foreach (var element in rootNodes.Values.ToArray())
  1089. {
  1090. SafeRemoveElement(element);
  1091. }
  1092. rootNodes.Clear();
  1093. rootGroupNodeElements.Clear();
  1094. }
  1095. else
  1096. {
  1097. elementsAddedToGroup = null;
  1098. elementsRemovedFromGroup = null;
  1099. Profiler.BeginSample("VFXView.SyncNodes:Delete");
  1100. var deletedControllers = rootNodes.Keys.Except(controller.nodes).ToArray();
  1101. foreach (var deletedController in deletedControllers)
  1102. {
  1103. SafeRemoveElement(rootNodes[deletedController]);
  1104. rootNodes.Remove(deletedController);
  1105. rootGroupNodeElements.Remove(deletedController);
  1106. }
  1107. Profiler.EndSample();
  1108. bool needOneListenToGeometry = !m_GeometrySet;
  1109. Profiler.BeginSample("VFXView.SyncNodes:Create");
  1110. bool selectionCleared = false;
  1111. foreach (var newController in controller.nodes.Except(rootNodes.Keys).ToArray())
  1112. {
  1113. VFXNodeUI newElement = null;
  1114. if (newController is VFXContextController)
  1115. {
  1116. newElement = new VFXContextUI();
  1117. }
  1118. else if (newController is VFXOperatorController)
  1119. {
  1120. newElement = new VFXOperatorUI();
  1121. }
  1122. else if (newController is VFXParameterNodeController)
  1123. {
  1124. newElement = new VFXParameterUI();
  1125. }
  1126. else
  1127. {
  1128. throw new InvalidOperationException("Can't find right ui for controller" + newController.GetType().Name);
  1129. }
  1130. Profiler.BeginSample("VFXView.SyncNodes:AddElement");
  1131. FastAddElement(newElement);
  1132. Profiler.EndSample();
  1133. rootNodes[newController] = newElement;
  1134. rootGroupNodeElements[newController] = newElement;
  1135. (newElement as ISettableControlledElement<VFXNodeController>).controller = newController;
  1136. if (needOneListenToGeometry)
  1137. {
  1138. needOneListenToGeometry = false;
  1139. newElement.RegisterCallback<GeometryChangedEvent>(OnOneNodeGeometryChanged);
  1140. }
  1141. newElement.controller.model.RefreshErrors(controller.graph);
  1142. if (m_UpdateSelectionWithNewNode)
  1143. {
  1144. if (!selectionCleared)
  1145. {
  1146. selectionCleared = true;
  1147. ClearSelection();
  1148. }
  1149. AddToSelection(newElement);
  1150. }
  1151. }
  1152. m_UpdateSelectionWithNewNode = false;
  1153. Profiler.EndSample();
  1154. elementsAddedToGroup = ElementAddedToGroupNode;
  1155. elementsRemovedFromGroup = ElementRemovedFromGroupNode;
  1156. }
  1157. Profiler.EndSample();
  1158. }
  1159. static FieldInfo s_Member_ContainerLayer = typeof(GraphView).GetField("m_ContainerLayers", BindingFlags.NonPublic | BindingFlags.Instance);
  1160. static MethodInfo s_Method_GetLayer = typeof(GraphView).GetMethod("GetLayer", BindingFlags.NonPublic | BindingFlags.Instance);
  1161. public void FastAddElement(GraphElement graphElement)
  1162. {
  1163. if (graphElement.IsResizable())
  1164. {
  1165. graphElement.hierarchy.Add(new Resizer());
  1166. graphElement.style.borderBottomWidth = 6;
  1167. }
  1168. int newLayer = graphElement.layer;
  1169. if (!(s_Member_ContainerLayer.GetValue(this) as IDictionary).Contains(newLayer))
  1170. {
  1171. AddLayer(newLayer);
  1172. }
  1173. (s_Method_GetLayer.Invoke(this, new object[] { newLayer }) as VisualElement).Add(graphElement);
  1174. }
  1175. bool m_UpdateUIBounds = false;
  1176. void UpdateUIBounds()
  1177. {
  1178. if (!m_GeometrySet) return;
  1179. if (m_InControllerChanged)
  1180. {
  1181. m_UpdateUIBounds = true;
  1182. return;
  1183. }
  1184. m_UpdateUIBounds = false;
  1185. if (panel != null)
  1186. {
  1187. panel.InternalValidateLayout();
  1188. controller.graph.UIInfos.uiBounds = GetElementsBounds(rootGroupNodeElements.Values.Concat(groupNodes.Values.Cast<GraphElement>()));
  1189. }
  1190. }
  1191. void SyncGroupNodes()
  1192. {
  1193. if (controller == null)
  1194. {
  1195. foreach (var kv in groupNodes)
  1196. {
  1197. RemoveElement(kv.Value);
  1198. }
  1199. groupNodes.Clear();
  1200. }
  1201. else
  1202. {
  1203. var deletedControllers = groupNodes.Keys.Except(controller.groupNodes).ToArray();
  1204. foreach (var deletedController in deletedControllers)
  1205. {
  1206. RemoveElement(groupNodes[deletedController]);
  1207. groupNodes.Remove(deletedController);
  1208. }
  1209. foreach (var newController in controller.groupNodes.Except(groupNodes.Keys))
  1210. {
  1211. var newElement = new VFXGroupNode();
  1212. FastAddElement(newElement);
  1213. newElement.controller = newController;
  1214. groupNodes.Add(newController, newElement);
  1215. }
  1216. }
  1217. }
  1218. void SyncStickyNotes()
  1219. {
  1220. if (controller == null)
  1221. {
  1222. foreach (var kv in stickyNotes)
  1223. {
  1224. SafeRemoveElement(kv.Value);
  1225. }
  1226. rootGroupNodeElements.Clear();
  1227. stickyNotes.Clear();
  1228. }
  1229. else
  1230. {
  1231. var deletedControllers = stickyNotes.Keys.Except(controller.stickyNotes).ToArray();
  1232. foreach (var deletedController in deletedControllers)
  1233. {
  1234. SafeRemoveElement(stickyNotes[deletedController]);
  1235. rootGroupNodeElements.Remove(deletedController);
  1236. stickyNotes.Remove(deletedController);
  1237. }
  1238. foreach (var newController in controller.stickyNotes.Except(stickyNotes.Keys))
  1239. {
  1240. var newElement = new VFXStickyNote();
  1241. newElement.controller = newController;
  1242. FastAddElement(newElement);
  1243. rootGroupNodeElements[newController] = newElement;
  1244. stickyNotes[newController] = newElement;
  1245. }
  1246. }
  1247. }
  1248. public void SafeRemoveElement(GraphElement element)
  1249. {
  1250. VFXGroupNode.inRemoveElement = true;
  1251. RemoveElement(element);
  1252. VFXGroupNode.inRemoveElement = false;
  1253. }
  1254. Dictionary<VFXDataEdgeController, VFXDataEdge> dataEdges = new Dictionary<VFXDataEdgeController, VFXDataEdge>();
  1255. Dictionary<VFXFlowEdgeController, VFXFlowEdge> flowEdges = new Dictionary<VFXFlowEdgeController, VFXFlowEdge>();
  1256. void SyncEdges(int change)
  1257. {
  1258. if (change == VFXViewController.Change.ui)
  1259. return; // for the moment ui changes don't have an impact on edges
  1260. if (change != VFXViewController.Change.flowEdge)
  1261. {
  1262. if (controller == null)
  1263. {
  1264. foreach (var element in dataEdges.Values)
  1265. {
  1266. RemoveElement(element);
  1267. }
  1268. dataEdges.Clear();
  1269. }
  1270. else
  1271. {
  1272. var deletedControllers = dataEdges.Keys.Except(controller.dataEdges).ToArray();
  1273. foreach (var deletedController in deletedControllers)
  1274. {
  1275. var edge = dataEdges[deletedController];
  1276. if (edge.input != null)
  1277. {
  1278. edge.input.Disconnect(edge);
  1279. }
  1280. if (edge.output != null)
  1281. {
  1282. edge.output.Disconnect(edge);
  1283. }
  1284. RemoveElement(edge);
  1285. dataEdges.Remove(deletedController);
  1286. }
  1287. foreach (var newController in controller.dataEdges.Except(dataEdges.Keys).ToArray())
  1288. {
  1289. // SyncEdges could be called before the VFXNodeUI have been created, it that case ignore them and trust that they will be created later when the
  1290. // nodes arrive.
  1291. if (GetNodeByController(newController.input.sourceNode) == null || GetNodeByController(newController.output.sourceNode) == null)
  1292. {
  1293. if (change != VFXViewController.Change.dataEdge)
  1294. {
  1295. Debug.LogError("Can't match nodes for a data edge after nodes should have been updated.");
  1296. }
  1297. continue;
  1298. }
  1299. var newElement = new VFXDataEdge();
  1300. FastAddElement(newElement);
  1301. newElement.controller = newController;
  1302. dataEdges.Add(newController, newElement);
  1303. if (newElement.input != null)
  1304. newElement.input.node.RefreshExpandedState();
  1305. if (newElement.output != null)
  1306. newElement.output.node.RefreshExpandedState();
  1307. }
  1308. }
  1309. }
  1310. if (change != VFXViewController.Change.dataEdge)
  1311. {
  1312. if (controller == null)
  1313. {
  1314. foreach (var element in flowEdges.Values)
  1315. {
  1316. RemoveElement(element);
  1317. }
  1318. flowEdges.Clear();
  1319. }
  1320. else
  1321. {
  1322. var deletedControllers = flowEdges.Keys.Except(controller.flowEdges).ToArray();
  1323. foreach (var deletedController in deletedControllers)
  1324. {
  1325. var edge = flowEdges[deletedController];
  1326. if (edge.input != null)
  1327. {
  1328. edge.input.Disconnect(edge);
  1329. }
  1330. if (edge.output != null)
  1331. {
  1332. edge.output.Disconnect(edge);
  1333. }
  1334. RemoveElement(edge);
  1335. flowEdges.Remove(deletedController);
  1336. }
  1337. foreach (var newController in controller.flowEdges.Except(flowEdges.Keys))
  1338. {
  1339. var newElement = new VFXFlowEdge();
  1340. FastAddElement(newElement);
  1341. newElement.controller = newController;
  1342. flowEdges.Add(newController, newElement);
  1343. }
  1344. }
  1345. }
  1346. }
  1347. public Vector2 ScreenToViewPosition(Vector2 position)
  1348. {
  1349. GUIView guiView = panel.InternalGetGUIView();
  1350. if (guiView == null)
  1351. return position;
  1352. return position - guiView.screenPosition.position;
  1353. }
  1354. public Vector2 ViewToScreenPosition(Vector2 position)
  1355. {
  1356. GUIView guiView = panel.InternalGetGUIView();
  1357. if (guiView == null)
  1358. return position;
  1359. return position + guiView.screenPosition.position;
  1360. }
  1361. void OnCreateNode(NodeCreationContext ctx)
  1362. {
  1363. GUIView guiView = panel.InternalGetGUIView();
  1364. if (guiView == null)
  1365. return;
  1366. Vector2 point = ScreenToViewPosition(ctx.screenMousePosition);
  1367. List<VisualElement> picked = new List<VisualElement>();
  1368. panel.PickAll(point, picked);
  1369. VFXContextUI context = picked.OfType<VFXContextUI>().FirstOrDefault();
  1370. if (context != null)
  1371. {
  1372. if (context.canHaveBlocks)
  1373. context.OnCreateBlock(point);
  1374. }
  1375. else
  1376. {
  1377. VFXDataEdge edge = picked.OfType<VFXDataEdge>().FirstOrDefault();
  1378. if (edge != null)
  1379. VFXFilterWindow.Show(VFXViewWindow.currentWindow, point, ctx.screenMousePosition, new VFXNodeProvider(controller, (d, v) => AddNodeOnEdge(d, v, edge.controller), null, new Type[] { typeof(VFXOperator) }));
  1380. else
  1381. VFXFilterWindow.Show(VFXViewWindow.currentWindow, point, ctx.screenMousePosition, m_NodeProvider);
  1382. }
  1383. }
  1384. public void CreateTemplateSystem(string path, Vector2 tPos, VFXGroupNode groupNode)
  1385. {
  1386. var resource = VisualEffectResource.GetResourceAtPath(path);
  1387. if (resource != null)
  1388. {
  1389. VFXViewController templateController = VFXViewController.GetController(resource, true);
  1390. templateController.useCount++;
  1391. var data = VFXCopy.SerializeElements(templateController.allChildren, templateController.graph.UIInfos.uiBounds);
  1392. VFXPaste.UnserializeAndPasteElements(controller, tPos, data, this, groupNode != null ? groupNode.controller : null);
  1393. templateController.useCount--;
  1394. }
  1395. }
  1396. void OnToggleCompile(ChangeEvent<bool> e)
  1397. {
  1398. VFXViewWindow.currentWindow.autoCompile = !VFXViewWindow.currentWindow.autoCompile;
  1399. }
  1400. void OnResyncMaterial()
  1401. {
  1402. controller.graph.Invalidate(VFXModel.InvalidationCause.kMaterialChanged);
  1403. }
  1404. void OnCompile()
  1405. {
  1406. VFXLibrary.LogUnsupportedSRP();
  1407. if (controller.model.isSubgraph)
  1408. controller.graph.RecompileIfNeeded(false, false);
  1409. else
  1410. {
  1411. VFXGraph.explicitCompile = true;
  1412. using (var reporter = new VFXCompileErrorReporter(controller.graph.errorManager))
  1413. {
  1414. VFXGraph.compileReporter = reporter;
  1415. AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller.model));
  1416. VFXGraph.compileReporter = null;
  1417. }
  1418. VFXGraph.explicitCompile = false;
  1419. }
  1420. }
  1421. void OnSave()
  1422. {
  1423. m_ComponentBoard?.DeactivateBoundsRecordingIfNeeded(); //Avoids saving the graph with unnecessary bounds computations
  1424. var graphToSave = new HashSet<VFXGraph>();
  1425. GetGraphsRecursively(controller.graph, graphToSave);
  1426. foreach (var graph in graphToSave)
  1427. {
  1428. if (EditorUtility.IsDirty(graph) || UnityEngine.Object.ReferenceEquals(graph, controller.graph))
  1429. {
  1430. graph.UpdateSubAssets();
  1431. try
  1432. {
  1433. VFXGraph.compilingInEditMode = !m_IsRuntimeMode;
  1434. graph.GetResource().WriteAsset();
  1435. }
  1436. finally
  1437. {
  1438. VFXGraph.compilingInEditMode = false;
  1439. }
  1440. }
  1441. }
  1442. }
  1443. void GetGraphsRecursively(VFXGraph start, HashSet<VFXGraph> graphs)
  1444. {
  1445. if (graphs.Contains(start))
  1446. return;
  1447. graphs.Add(start);
  1448. foreach (var child in start.children)
  1449. {
  1450. if (child is VFXSubgraphOperator ope)
  1451. {
  1452. if (ope.subgraph != null)
  1453. {
  1454. var graph = ope.subgraph.GetResource().GetOrCreateGraph();
  1455. GetGraphsRecursively(graph, graphs);
  1456. }
  1457. }
  1458. else if (child is VFXSubgraphContext subCtx)
  1459. {
  1460. if (subCtx.subgraph != null)
  1461. {
  1462. var graph = subCtx.subgraph.GetResource().GetOrCreateGraph();
  1463. GetGraphsRecursively(graph, graphs);
  1464. }
  1465. }
  1466. else if (child is VFXContext ctx)
  1467. {
  1468. foreach (var block in ctx.children.Cast<VFXBlock>())
  1469. {
  1470. if (block is VFXSubgraphBlock subBlock)
  1471. {
  1472. if (subBlock.subgraph != null)
  1473. {
  1474. var graph = subBlock.subgraph.GetResource().GetOrCreateGraph();
  1475. GetGraphsRecursively(graph, graphs);
  1476. }
  1477. }
  1478. }
  1479. }
  1480. }
  1481. }
  1482. public EventPropagation Compile()
  1483. {
  1484. OnCompile();
  1485. return EventPropagation.Stop;
  1486. }
  1487. void AddVFXParameter(Vector2 pos, VFXParameterController parameterController, VFXGroupNode groupNode)
  1488. {
  1489. if (controller == null || parameterController == null) return;
  1490. controller.AddVFXParameter(pos, parameterController, groupNode != null ? groupNode.controller : null);
  1491. }
  1492. public EventPropagation Resync()
  1493. {
  1494. foreach (var node in rootNodes.Values)
  1495. node.RemoveFromHierarchy();
  1496. rootNodes.Clear();
  1497. foreach (var node in nodes.ToList())
  1498. node.RemoveFromHierarchy();
  1499. foreach (var edge in dataEdges.Values)
  1500. edge.RemoveFromHierarchy();
  1501. dataEdges.Clear();
  1502. foreach (var edge in flowEdges.Values)
  1503. edge.RemoveFromHierarchy();
  1504. flowEdges.Clear();
  1505. foreach (var edge in edges.ToList())
  1506. edge.RemoveFromHierarchy();
  1507. if (controller != null)
  1508. controller.ForceReload();
  1509. return EventPropagation.Stop;
  1510. }
  1511. public EventPropagation OutputToDot()
  1512. {
  1513. if (controller == null) return EventPropagation.Stop;
  1514. DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.None, "expGraph_None.dot");
  1515. return EventPropagation.Stop;
  1516. }
  1517. public EventPropagation OutputToDotReduced()
  1518. {
  1519. if (controller == null) return EventPropagation.Stop;
  1520. DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.Reduction, "expGraph_Reduction.dot");
  1521. return EventPropagation.Stop;
  1522. }
  1523. public EventPropagation OutputToDotConstantFolding()
  1524. {
  1525. if (controller == null) return EventPropagation.Stop;
  1526. DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.ConstantFolding, "expGraph_ConstantFolding.dot");
  1527. return EventPropagation.Stop;
  1528. }
  1529. IEnumerable<VisualEffect> GetActiveComponents()
  1530. {
  1531. if (attachedComponent != null)
  1532. yield return attachedComponent;
  1533. else
  1534. {
  1535. foreach (var component in UnityEngine.VFX.VFXManager.GetComponents())
  1536. yield return component;
  1537. }
  1538. }
  1539. public EventPropagation ReinitComponents()
  1540. {
  1541. foreach (var component in GetActiveComponents())
  1542. component.Reinit();
  1543. return EventPropagation.Stop;
  1544. }
  1545. public EventPropagation ReinitAndPlayComponents()
  1546. {
  1547. foreach (var component in GetActiveComponents())
  1548. {
  1549. component.Reinit();
  1550. component.Play();
  1551. }
  1552. return EventPropagation.Stop;
  1553. }
  1554. public IEnumerable<VFXContextUI> GetAllContexts()
  1555. {
  1556. foreach (var layer in contentViewContainer.Children())
  1557. {
  1558. foreach (var element in layer.Children())
  1559. {
  1560. if (element is VFXContextUI)
  1561. {
  1562. yield return element as VFXContextUI;
  1563. }
  1564. }
  1565. }
  1566. }
  1567. public IEnumerable<VFXNodeUI> GetAllNodes()
  1568. {
  1569. foreach (var layer in contentViewContainer.Children())
  1570. {
  1571. foreach (var element in layer.Children())
  1572. {
  1573. if (element is VFXNodeUI)
  1574. {
  1575. yield return element as VFXNodeUI;
  1576. }
  1577. }
  1578. }
  1579. }
  1580. public override List<Port> GetCompatiblePorts(Port startAnchor, NodeAdapter nodeAdapter)
  1581. {
  1582. if (controller == null) return null;
  1583. if (startAnchor is VFXDataAnchor)
  1584. {
  1585. var controllers = controller.GetCompatiblePorts((startAnchor as VFXDataAnchor).controller, nodeAdapter);
  1586. return controllers.Select(t => (Port)GetDataAnchorByController(t as VFXDataAnchorController)).ToList();
  1587. }
  1588. else
  1589. {
  1590. var controllers = controller.GetCompatiblePorts((startAnchor as VFXFlowAnchor).controller, nodeAdapter);
  1591. return controllers.Select(t => (Port)GetFlowAnchorByController(t as VFXFlowAnchorController)).ToList();
  1592. }
  1593. }
  1594. public IEnumerable<VFXFlowAnchor> GetAllFlowAnchors(bool input, bool output)
  1595. {
  1596. foreach (var context in GetAllContexts())
  1597. {
  1598. foreach (VFXFlowAnchor anchor in context.GetFlowAnchors(input, output))
  1599. {
  1600. yield return anchor;
  1601. }
  1602. }
  1603. }
  1604. void VFXElementResized(VisualElement element)
  1605. {
  1606. if (element is IVFXResizable)
  1607. {
  1608. (element as IVFXResizable).OnResized();
  1609. }
  1610. }
  1611. GraphViewChange VFXGraphViewChanged(GraphViewChange change)
  1612. {
  1613. if (change.movedElements != null && change.movedElements.Count > 0)
  1614. {
  1615. HashSet<IVFXMovable> movables = new HashSet<IVFXMovable>(change.movedElements.OfType<IVFXMovable>());
  1616. foreach (var groupNode in groupNodes.Values)
  1617. {
  1618. var containedElements = groupNode.containedElements;
  1619. if (containedElements != null && containedElements.Intersect(change.movedElements).Count() > 0)
  1620. {
  1621. groupNode.UpdateGeometryFromContent();
  1622. movables.Add(groupNode);
  1623. }
  1624. }
  1625. foreach (var groupNode in change.movedElements.OfType<VFXGroupNode>())
  1626. {
  1627. var containedElements = groupNode.containedElements;
  1628. if (containedElements != null)
  1629. {
  1630. foreach (var node in containedElements.OfType<IVFXMovable>())
  1631. {
  1632. movables.Add(node);
  1633. }
  1634. }
  1635. }
  1636. foreach (var movable in movables)
  1637. {
  1638. movable.OnMoved();
  1639. }
  1640. }
  1641. else if (change.elementsToRemove != null)
  1642. {
  1643. controller.Remove(change.elementsToRemove.OfType<IControlledElement>().Where(t => t.controller != null).Select(t => t.controller));
  1644. foreach (var dataEdge in change.elementsToRemove.OfType<VFXDataEdge>())
  1645. {
  1646. RemoveElement(dataEdge);
  1647. dataEdges.Remove(dataEdge.controller);
  1648. }
  1649. }
  1650. return change;
  1651. }
  1652. public VFXNodeUI GetNodeByController(VFXNodeController controller)
  1653. {
  1654. if (controller is VFXBlockController)
  1655. {
  1656. var blockController = (controller as VFXBlockController);
  1657. VFXContextUI context = GetNodeByController(blockController.contextController) as VFXContextUI;
  1658. return context.GetAllBlocks().FirstOrDefault(t => t.controller == blockController);
  1659. }
  1660. return GetAllNodes().FirstOrDefault(t => t.controller == controller);
  1661. }
  1662. public VFXDataAnchor GetDataAnchorByController(VFXDataAnchorController controller)
  1663. {
  1664. if (controller == null)
  1665. return null;
  1666. VFXNodeUI node = GetNodeByController(controller.sourceNode);
  1667. if (node == null)
  1668. {
  1669. Debug.LogError("Can't find the node for a given node controller");
  1670. return null;
  1671. }
  1672. VFXDataAnchor anchor = node.GetPorts(controller.direction == Direction.Input, controller.direction == Direction.Output).FirstOrDefault(t => t.controller == controller);
  1673. if (anchor == null)
  1674. {
  1675. // Can happen because the order of the DataWatch is not controlled
  1676. node.ForceUpdate();
  1677. anchor = node.GetPorts(controller.direction == Direction.Input, controller.direction == Direction.Output).FirstOrDefault(t => t.controller == controller);
  1678. }
  1679. return anchor;
  1680. }
  1681. public VFXFlowAnchor GetFlowAnchorByController(VFXFlowAnchorController controller)
  1682. {
  1683. if (controller == null)
  1684. return null;
  1685. return GetAllFlowAnchors(controller.direction == Direction.Input, controller.direction == Direction.Output).Where(t => t.controller == controller).FirstOrDefault();
  1686. }
  1687. public IEnumerable<VFXDataAnchor> GetAllDataAnchors(bool input, bool output)
  1688. {
  1689. foreach (var layer in contentViewContainer.Children())
  1690. {
  1691. foreach (var element in layer.Children())
  1692. {
  1693. if (element is VFXNodeUI)
  1694. {
  1695. var ope = element as VFXNodeUI;
  1696. foreach (VFXDataAnchor anchor in ope.GetPorts(input, output))
  1697. yield return anchor;
  1698. if (element is VFXContextUI)
  1699. {
  1700. var context = element as VFXContextUI;
  1701. foreach (VFXBlockUI block in context.GetAllBlocks())
  1702. {
  1703. foreach (VFXDataAnchor anchor in block.GetPorts(input, output))
  1704. yield return anchor;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. }
  1710. }
  1711. public VFXDataEdge GetDataEdgeByController(VFXDataEdgeController controller)
  1712. {
  1713. foreach (var layer in contentViewContainer.Children())
  1714. {
  1715. foreach (var element in layer.Children())
  1716. {
  1717. if (element is VFXDataEdge)
  1718. {
  1719. VFXDataEdge candidate = element as VFXDataEdge;
  1720. if (candidate.controller == controller)
  1721. return candidate;
  1722. }
  1723. }
  1724. }
  1725. return null;
  1726. }
  1727. public void UpdateGlobalSelection()
  1728. {
  1729. if (controller == null) return;
  1730. var objectSelected = selection.OfType<VFXNodeUI>().Select(t => t.controller.model).Concat(selection.OfType<VFXContextUI>().Select(t => t.controller.model).Cast<VFXModel>()).Where(t => t != null).ToArray();
  1731. if (objectSelected.Length > 0)
  1732. {
  1733. Selection.objects = objectSelected;
  1734. Selection.objects = objectSelected;
  1735. return;
  1736. }
  1737. var blackBoardSelected = selection.OfType<BlackboardField>().Select(t => t.GetFirstAncestorOfType<VFXBlackboardRow>().controller.model).ToArray();
  1738. if (blackBoardSelected.Length > 0)
  1739. {
  1740. Selection.objects = blackBoardSelected;
  1741. return;
  1742. }
  1743. }
  1744. void SelectAsset()
  1745. {
  1746. if (Selection.activeObject != controller.model)
  1747. {
  1748. Selection.activeObject = controller.model.visualEffectObject;
  1749. EditorGUIUtility.PingObject(controller.model.visualEffectObject);
  1750. }
  1751. }
  1752. void Checkout()
  1753. {
  1754. Task task = Provider.Checkout(controller.model.visualEffectObject, CheckoutMode.Both);
  1755. task.Wait();
  1756. OnFocus();
  1757. }
  1758. void ElementAddedToGroupNode(Group groupNode, IEnumerable<GraphElement> elements)
  1759. {
  1760. (groupNode as VFXGroupNode).ElementsAddedToGroupNode(elements);
  1761. }
  1762. void ElementRemovedFromGroupNode(Group groupNode, IEnumerable<GraphElement> elements)
  1763. {
  1764. (groupNode as VFXGroupNode).ElementsRemovedFromGroupNode(elements);
  1765. }
  1766. void GroupNodeTitleChanged(Group groupNode, string title)
  1767. {
  1768. (groupNode as VFXGroupNode).GroupNodeTitleChanged(title);
  1769. }
  1770. private void AddRangeToSelection(List<ISelectable> selectables)
  1771. {
  1772. selectables.ForEach(base.AddToSelection);
  1773. UpdateGlobalSelection();
  1774. }
  1775. public override void AddToSelection(ISelectable selectable)
  1776. {
  1777. base.AddToSelection(selectable);
  1778. UpdateGlobalSelection();
  1779. }
  1780. public override void RemoveFromSelection(ISelectable selectable)
  1781. {
  1782. base.RemoveFromSelection(selectable);
  1783. UpdateGlobalSelection();
  1784. }
  1785. public override void ClearSelection()
  1786. {
  1787. bool selectionEmpty = selection.Count() == 0;
  1788. base.ClearSelection();
  1789. if (!selectionEmpty)
  1790. UpdateGlobalSelection();
  1791. }
  1792. VFXBlackboard m_Blackboard;
  1793. VFXComponentBoard m_ComponentBoard;
  1794. public VFXBlackboard blackboard
  1795. {
  1796. get { return m_Blackboard; }
  1797. }
  1798. protected internal override bool canCopySelection
  1799. {
  1800. get { return selection.OfType<VFXNodeUI>().Any() || selection.OfType<Group>().Any() || selection.OfType<VFXContextUI>().Any(t => !(t.controller.model is VFXBlockSubgraphContext)) || selection.OfType<VFXStickyNote>().Any(); }
  1801. }
  1802. IEnumerable<Controller> ElementsToController(IEnumerable<GraphElement> elements)
  1803. {
  1804. return elements.OfType<IControlledElement>().Select(t => t.controller);
  1805. }
  1806. void CollectElements(IEnumerable<GraphElement> elements, HashSet<GraphElement> elementsToCopySet)
  1807. {
  1808. foreach (var element in elements)
  1809. {
  1810. if (element is Group)
  1811. {
  1812. CollectElements((element as Group).containedElements, elementsToCopySet);
  1813. elementsToCopySet.Add(element);
  1814. }
  1815. else if (element is Node || element is VFXContextUI || element is VFXStickyNote)
  1816. {
  1817. elementsToCopySet.Add(element);
  1818. }
  1819. }
  1820. }
  1821. protected internal override void CollectCopyableGraphElements(IEnumerable<GraphElement> elements, HashSet<GraphElement> elementsToCopySet)
  1822. {
  1823. CollectElements(elements, elementsToCopySet);
  1824. var nodeuis = new HashSet<VFXNodeUI>(elementsToCopySet.SelectMany(t => t.Query().OfType<VFXNodeUI>().ToList()));
  1825. var contextuis = new HashSet<VFXContextUI>(elementsToCopySet.OfType<VFXContextUI>());
  1826. foreach (var edge in edges.ToList())
  1827. {
  1828. if (edge is VFXDataEdge)
  1829. {
  1830. if (nodeuis.Contains(edge.input.GetFirstAncestorOfType<VFXNodeUI>()) && nodeuis.Contains(edge.output.GetFirstAncestorOfType<VFXNodeUI>()))
  1831. {
  1832. elementsToCopySet.Add(edge);
  1833. }
  1834. }
  1835. else
  1836. {
  1837. if (contextuis.Contains(edge.input.GetFirstAncestorOfType<VFXContextUI>()) && contextuis.Contains(edge.output.GetFirstAncestorOfType<VFXContextUI>()))
  1838. {
  1839. elementsToCopySet.Add(edge);
  1840. }
  1841. }
  1842. }
  1843. }
  1844. Rect GetElementsBounds(IEnumerable<GraphElement> elements)
  1845. {
  1846. Rect[] elementBounds = elements.Where(t => !(t is VFXEdge)).Select(t => contentViewContainer.WorldToLocal(t.worldBound)).ToArray();
  1847. if (elementBounds.Length < 1) return Rect.zero;
  1848. Rect bounds = elementBounds[0];
  1849. for (int i = 1; i < elementBounds.Length; ++i)
  1850. {
  1851. bounds = Rect.MinMaxRect(Mathf.Min(elementBounds[i].xMin, bounds.xMin), Mathf.Min(elementBounds[i].yMin, bounds.yMin), Mathf.Max(elementBounds[i].xMax, bounds.xMax), Mathf.Max(elementBounds[i].yMax, bounds.yMax));
  1852. }
  1853. // Round to avoid changes in the asset because of the zoom level.
  1854. bounds.x = Mathf.Round(bounds.x);
  1855. bounds.y = Mathf.Round(bounds.y);
  1856. bounds.width = Mathf.Round(bounds.width);
  1857. bounds.height = Mathf.Round(bounds.height);
  1858. return bounds;
  1859. }
  1860. public string SerializeElements(IEnumerable<GraphElement> elements)
  1861. {
  1862. Profiler.BeginSample("VFXCopy.SerializeElements");
  1863. string result = VFXCopy.SerializeElements(ElementsToController(elements), GetElementsBounds(elements));
  1864. Profiler.EndSample();
  1865. return result;
  1866. }
  1867. public EventPropagation DuplicateSelectionWithEdges()
  1868. {
  1869. List<Controller> sourceControllers = selection.OfType<IControlledElement>().Select(t => t.controller).ToList();
  1870. Rect bounds = GetElementsBounds(selection.OfType<IControlledElement>().OfType<GraphElement>());
  1871. object result = VFXCopy.Copy(sourceControllers, bounds);
  1872. var targetControllers = new List<VFXNodeController>();
  1873. VFXPaste.Paste(controller, pasteCenter, result, this, null, targetControllers);
  1874. ClearSelection();
  1875. for (int i = 0; i < sourceControllers.Count; ++i)
  1876. {
  1877. if (targetControllers[i] != null)
  1878. {
  1879. CopyInputLinks(sourceControllers[i] as VFXNodeController, targetControllers[i]);
  1880. if (targetControllers[i] is VFXBlockController blkController)
  1881. AddToSelection((rootNodes[blkController.contextController] as VFXContextUI).GetAllBlocks().First(t => t.controller == blkController));
  1882. else
  1883. AddToSelection(rootNodes[targetControllers[i]]);
  1884. }
  1885. }
  1886. return EventPropagation.Stop;
  1887. }
  1888. public void AddToSelection(VFXModel model, int id)
  1889. {
  1890. VFXNodeController nodeController = controller.GetRootNodeController(model, id);
  1891. if (nodeController != null)
  1892. {
  1893. AddToSelection(rootNodes[nodeController]);
  1894. }
  1895. }
  1896. public void AddParameterToSelection(VFXParameter parameter)
  1897. {
  1898. VFXParameterController parameterController = controller.GetParameterController(parameter);
  1899. if (parameterController != null)
  1900. {
  1901. m_Blackboard.AddToSelection(m_Blackboard.GetRowFromController(parameterController).field);
  1902. }
  1903. }
  1904. void CopyInputLinks(VFXNodeController sourceController, VFXNodeController targetController)
  1905. {
  1906. foreach (var st in sourceController.inputPorts.Zip(targetController.inputPorts, (s, t) => new { source = s, target = t }))
  1907. {
  1908. CopyInputLinks(st.source, st.target);
  1909. }
  1910. if (sourceController is VFXContextController sourceContext && targetController is VFXContextController targetContext)
  1911. {
  1912. foreach (var st in sourceContext.blockControllers.Zip(targetContext.blockControllers, (s, t) => new { source = s, target = t }))
  1913. {
  1914. CopyInputLinks(st.source, st.target);
  1915. }
  1916. }
  1917. }
  1918. void CopyInputLinks(VFXDataAnchorController sourceSlot, VFXDataAnchorController targetSlot)
  1919. {
  1920. if (sourceSlot.portType != targetSlot.portType)
  1921. return;
  1922. if (sourceSlot.HasLink())
  1923. controller.CreateLink(targetSlot, controller.dataEdges.First(t => t.input == sourceSlot).output);
  1924. }
  1925. Vector2 pasteCenter
  1926. {
  1927. get
  1928. {
  1929. Vector2 center = layout.size * 0.5f;
  1930. center = this.ChangeCoordinatesTo(contentViewContainer, center);
  1931. return center;
  1932. }
  1933. }
  1934. private bool VFXCanPaste(string data)
  1935. {
  1936. return VFXPaste.CanPaste(this, data);
  1937. }
  1938. public void UnserializeAndPasteElements(string operationName, string data)
  1939. {
  1940. Profiler.BeginSample("VFXPaste.VFXPaste.UnserializeAndPasteElements");
  1941. VFXPaste.UnserializeAndPasteElements(controller, pasteCenter, data, this);
  1942. Profiler.EndSample();
  1943. }
  1944. private bool TryGetOverlappingContextAbove(VFXContextUI context, out VFXContextUI overlappingContext, out float distance)
  1945. {
  1946. var rect = context.GetPosition();
  1947. var posY = context.controller.model.position.y;
  1948. var overlappingContexts = new Dictionary<VFXContextUI, float>();
  1949. foreach (var ctx in GetAllContexts())
  1950. {
  1951. if (ctx == context)
  1952. {
  1953. continue;
  1954. }
  1955. var ctxRect = ctx.GetPosition();
  1956. var ctxPosY = ctx.controller.model.position.y;
  1957. // Skip contexts that are side by side
  1958. if (rect.xMin - ctxRect.xMax > -5 || rect.xMax - ctxRect.xMin < 5)
  1959. {
  1960. continue;
  1961. }
  1962. distance = posY - ctxPosY - ctxRect.height;
  1963. if (distance < 0 && posY > ctxRect.yMin)
  1964. {
  1965. overlappingContexts[ctx] = -distance;
  1966. }
  1967. }
  1968. if (overlappingContexts.Any())
  1969. {
  1970. var keyPair = overlappingContexts.OrderByDescending(x => x.Value).First();
  1971. overlappingContext = keyPair.Key;
  1972. distance = keyPair.Value;
  1973. return true;
  1974. }
  1975. distance = 0f;
  1976. overlappingContext = null;
  1977. return false;
  1978. }
  1979. public void PushUnderContext(VFXContextUI context, float size)
  1980. {
  1981. if (size < 5) return;
  1982. foreach (var edge in edges.OfType<VFXFlowEdge>().SkipWhile(x => x.output.GetFirstAncestorOfType<VFXContextUI>() != context))
  1983. {
  1984. context = edge.input.GetFirstAncestorOfType<VFXContextUI>();
  1985. if (TryGetOverlappingContextAbove(context, out var aboveContext, out var distance))
  1986. {
  1987. var rect = context.GetPosition();
  1988. context.controller.position = new Vector2(rect.x, rect.y + distance);
  1989. }
  1990. }
  1991. }
  1992. bool canGroupSelection
  1993. {
  1994. get
  1995. {
  1996. return canCopySelection && !selection.Any(t => t is Group);
  1997. }
  1998. }
  1999. void OnEnterPanel(AttachToPanelEvent e)
  2000. {
  2001. Undo.undoRedoPerformed += OnUndoPerformed;
  2002. }
  2003. void OnLeavePanel(DetachFromPanelEvent e)
  2004. {
  2005. Undo.undoRedoPerformed -= OnUndoPerformed;
  2006. }
  2007. private void OnKeyDownEvent(KeyDownEvent evt)
  2008. {
  2009. if (evt.keyCode == KeyCode.D && evt.modifiers == EventModifiers.Control)
  2010. {
  2011. DuplicateBlackboardFieldSelection();
  2012. DuplicateBlackBoardCategorySelection();
  2013. }
  2014. }
  2015. public void ValidateCommand(ValidateCommandEvent evt)
  2016. {
  2017. if (evt.commandName == "SelectAll")
  2018. {
  2019. evt.StopPropagation();
  2020. if (evt.imguiEvent != null)
  2021. {
  2022. evt.imguiEvent.Use();
  2023. }
  2024. }
  2025. }
  2026. public void ExecuteCommand(ExecuteCommandEvent e)
  2027. {
  2028. if (e.commandName == "SelectAll")
  2029. {
  2030. ClearSelection();
  2031. AddRangeToSelection(graphElements.Where(x => x is not VFXSystemBorder).OfType<ISelectable>().ToList());
  2032. e.StopPropagation();
  2033. }
  2034. }
  2035. void GroupSelection()
  2036. {
  2037. controller.GroupNodes(selection.OfType<ISettableControlledElement<VFXNodeController>>().Select(t => t.controller));
  2038. }
  2039. void AddStickyNote(Vector2 position, VFXGroupNode group = null)
  2040. {
  2041. position = contentViewContainer.WorldToLocal(position);
  2042. controller.AddStickyNote(position, group != null ? group.controller : null);
  2043. }
  2044. void OnCreateNodeInGroupNode(DropdownMenuAction e)
  2045. {
  2046. //The targeted groupnode will be determined by a PickAll later
  2047. VFXFilterWindow.Show(VFXViewWindow.currentWindow, e.eventInfo.mousePosition, ViewToScreenPosition(e.eventInfo.mousePosition), m_NodeProvider);
  2048. }
  2049. void OnEnterSubgraph(DropdownMenuAction e)
  2050. {
  2051. var node = e.userData as VFXModel;
  2052. if (node is VFXSubgraphOperator subGraph)
  2053. {
  2054. VFXViewWindow.currentWindow.PushResource(subGraph.subgraph.GetResource());
  2055. }
  2056. else if (node is VFXSubgraphBlock subGraph2)
  2057. {
  2058. VFXViewWindow.currentWindow.PushResource(subGraph2.subgraph.GetResource());
  2059. }
  2060. else if (node is VFXSubgraphContext subGraph3)
  2061. {
  2062. VFXViewWindow.currentWindow.PushResource(subGraph3.subgraph.GetResource());
  2063. }
  2064. }
  2065. void OnCreateNodeOnEdge(DropdownMenuAction e)
  2066. {
  2067. VFXFilterWindow.Show(VFXViewWindow.currentWindow, e.eventInfo.mousePosition, ViewToScreenPosition(e.eventInfo.mousePosition), new VFXNodeProvider(controller, (d, v) => AddNodeOnEdge(d, v, e.userData as VFXDataEdgeController), null, new Type[] { typeof(VFXOperator) }));
  2068. }
  2069. void AddNodeOnEdge(VFXNodeProvider.Descriptor desc, Vector2 position, VFXDataEdgeController edge)
  2070. {
  2071. position = this.ChangeCoordinatesTo(contentViewContainer, position);
  2072. position.x -= 60;
  2073. position.y -= 60;
  2074. position = contentViewContainer.ChangeCoordinatesTo(this, position);
  2075. var newNodeController = AddNode(desc, position);
  2076. if (newNodeController == null)
  2077. return;
  2078. foreach (var outputPort in newNodeController.outputPorts)
  2079. {
  2080. if (controller.CreateLink(edge.input, outputPort))
  2081. break;
  2082. }
  2083. foreach (var inputPort in newNodeController.inputPorts)
  2084. {
  2085. if (controller.CreateLink(inputPort, edge.output))
  2086. break;
  2087. }
  2088. }
  2089. public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
  2090. {
  2091. if (controller == null || !IsAssetEditable())
  2092. return;
  2093. if (evt.target is VFXGroupNode || evt.target is VFXSystemBorder) // Default behaviour only shows the OnCreateNode if the target is the view itself.
  2094. evt.target = this;
  2095. base.BuildContextualMenu(evt);
  2096. Vector2 mousePosition = evt.mousePosition;
  2097. if (evt.target is VFXNodeUI node)
  2098. {
  2099. evt.menu.InsertAction(evt.target is VFXContextUI ? 1 : 0, "Group Selection", (e) => { GroupSelection(); },
  2100. (e) => { return canGroupSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
  2101. if ((node.controller.model is VFXSubgraphOperator subOp && subOp.subgraph != null) || (node.controller.model is VFXSubgraphContext subCont && subCont.subgraph != null) || (node.controller.model is VFXSubgraphBlock subBlk && subBlk.subgraph != null))
  2102. {
  2103. evt.menu.AppendAction("Enter Subgraph", OnEnterSubgraph, e => DropdownMenuAction.Status.Normal, node.controller.model);
  2104. }
  2105. evt.menu.AppendAction("Clear Ignored Errors", a => node.controller.model.ClearIgnoredErrors(), node.controller.model.HasIgnoredErrors() ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
  2106. }
  2107. if (evt.target is VFXDataEdge edge)
  2108. {
  2109. evt.menu.InsertAction(0, "Create Node", OnCreateNodeOnEdge, t => DropdownMenuAction.Status.Normal, edge.controller);
  2110. }
  2111. if (evt.target is VFXView)
  2112. {
  2113. evt.menu.InsertAction(1, "Create Sticky Note", (e) => { AddStickyNote(mousePosition); }, (e) => DropdownMenuAction.Status.Normal);
  2114. if (evt.triggerEvent is IMouseEvent)
  2115. {
  2116. foreach (var system in m_Systems)
  2117. {
  2118. Rect bounds = system.worldBound;
  2119. if (bounds.Contains((evt.triggerEvent as IMouseEvent).mousePosition))
  2120. {
  2121. evt.menu.InsertSeparator("", 2);
  2122. evt.menu.InsertAction(3, string.IsNullOrEmpty(system.controller.title) ? "Name System" : "Rename System", a => system.OnRename(), e => DropdownMenuAction.Status.Normal);
  2123. break;
  2124. }
  2125. }
  2126. }
  2127. if (VFXViewWindow.currentWindow != null && VFXViewWindow.currentWindow.resourceHistory.Count() > 0)
  2128. {
  2129. evt.menu.AppendAction(" Back To Parent Graph", e => VFXViewWindow.currentWindow.PopResource());
  2130. }
  2131. }
  2132. if (evt.target is VFXContextUI)
  2133. {
  2134. var context = evt.target as VFXContextUI;
  2135. evt.menu.InsertSeparator("", 2);
  2136. evt.menu.InsertAction(3, string.IsNullOrEmpty(context.controller.model.label) ? "Name Context" : "Rename Context", a => context.OnRename(), e => DropdownMenuAction.Status.Normal);
  2137. }
  2138. if (selection.OfType<VFXNodeUI>().Any() && evt.target is VFXNodeUI)
  2139. {
  2140. if (selection.OfType<VFXOperatorUI>().Any() && !selection.OfType<VFXNodeUI>().Any(t => !(t is VFXOperatorUI) && !(t is VFXParameterUI)))
  2141. evt.menu.InsertAction(3, "Convert To Subgraph Operator", ToSubgraphOperator, e => DropdownMenuAction.Status.Normal);
  2142. else if (SelectionHasCompleteSystems())
  2143. evt.menu.InsertAction(3, "Convert To Subgraph", ToSubgraphContext, e => DropdownMenuAction.Status.Normal);
  2144. else if (selection.OfType<VFXBlockUI>().Any() && selection.OfType<VFXBlockUI>().Select(t => t.context).Distinct().Count() == 1)
  2145. {
  2146. evt.menu.InsertAction(3, "Convert to Subgraph Block", ToSubgraphBlock, e => DropdownMenuAction.Status.Normal);
  2147. }
  2148. }
  2149. if (evt.target is GraphView || evt.target is Node || evt.target is Group)
  2150. {
  2151. evt.menu.AppendAction("Duplicate with edges", (a) => { DuplicateSelectionWithEdges(); },
  2152. (a) => { return canDuplicateSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
  2153. evt.menu.AppendSeparator();
  2154. }
  2155. if (selection.OfType<VFXOperatorUI>().Any(t => !t.superCollapsed))
  2156. evt.menu.AppendAction("Collapse Operators", CollapseOperator, e => DropdownMenuAction.Status.Normal, true);
  2157. if (selection.OfType<VFXOperatorUI>().Any(t => t.superCollapsed))
  2158. evt.menu.AppendAction("Uncollapse Operators", CollapseOperator, e => DropdownMenuAction.Status.Normal, false);
  2159. if (selection.OfType<VFXStickyNote>().Any() && evt.menu.MenuItems().OfType<DropdownMenuAction>().All(x => x.name != "Delete"))
  2160. {
  2161. evt.menu.AppendSeparator();
  2162. evt.menu.AppendAction("Delete", OnDeleteStickyNote, e => canDeleteSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
  2163. }
  2164. if (selection.OfType<VFXBlackboardCategory>().Any())
  2165. {
  2166. evt.menu.AppendSeparator();
  2167. evt.menu.AppendAction("Duplicate %d", OnDuplicateBlackBoardCategory, e => canDeleteSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
  2168. }
  2169. if (evt.target is GraphView || evt.target is Node)
  2170. {
  2171. var copyMenu = evt.menu.MenuItems().OfType<DropdownMenuAction>().SingleOrDefault(x => x.name == "Copy");
  2172. if (copyMenu != null)
  2173. {
  2174. var index = evt.menu.MenuItems().IndexOf(copyMenu);
  2175. evt.menu.InsertAction(index + 1, "Paste", (a) => { PasteCallback(); }, (a) => { return canPaste ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
  2176. }
  2177. }
  2178. }
  2179. static readonly string s_DeleteEventCommandName = GetDeleteEventCommandName();
  2180. static string GetDeleteEventCommandName()
  2181. {
  2182. var fieldInfo = Type.GetType("UnityEngine.EventCommandNames, UnityEngine")?.GetField("Delete", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
  2183. if (fieldInfo != null)
  2184. {
  2185. if (fieldInfo.GetValue(null) is string commandName)
  2186. {
  2187. return commandName;
  2188. }
  2189. Debug.Log("API has changed, Delete command name field is either null or not a string anymore");
  2190. }
  2191. else
  2192. {
  2193. Debug.Log("API has changed, could not retrieve Delete command name field using reflection");
  2194. }
  2195. return "Delete";
  2196. }
  2197. void OnDeleteStickyNote(DropdownMenuAction menuAction)
  2198. {
  2199. using var ev = ExecuteCommandEvent.GetPooled(s_DeleteEventCommandName);
  2200. SendEvent(ev);
  2201. }
  2202. private void OnDuplicateBlackBoardCategory(DropdownMenuAction obj)
  2203. {
  2204. DuplicateBlackBoardCategorySelection();
  2205. }
  2206. void CollapseOperator(DropdownMenuAction a)
  2207. {
  2208. bool collapse = (bool)a.userData;
  2209. foreach (var ope in selection.OfType<VFXOperatorUI>())
  2210. ope.controller.superCollapsed = collapse;
  2211. }
  2212. public bool SelectionHasCompleteSystems()
  2213. {
  2214. HashSet<VFXContextUI> selectedContextUIs = new HashSet<VFXContextUI>(selection.OfType<VFXContextUI>());
  2215. if (selectedContextUIs.Count() < 1)
  2216. return false;
  2217. var relatedContext = selectedContextUIs.Select(t => t.controller.model);
  2218. //Adding manually VFXBasicGPUEvent, it doesn't appears as dependency.
  2219. var outputContextDataFromGPUEvent = relatedContext.OfType<VFXBasicGPUEvent>().SelectMany(o => o.outputContexts);
  2220. relatedContext = relatedContext.Concat(outputContextDataFromGPUEvent);
  2221. var selectedContextDatas = relatedContext.Select(o => o.GetData()).Where(o => o != null);
  2222. var selectedContextDependencies = selectedContextDatas.SelectMany(o => o.allDependenciesIncludingNotCompilable);
  2223. var allDatas = selectedContextDatas.Concat(selectedContextDependencies);
  2224. var allDatasHash = new HashSet<VFXData>(allDatas);
  2225. foreach (var context in GetAllContexts())
  2226. {
  2227. var model = context.controller.model;
  2228. if (model is VFXBlockSubgraphContext)
  2229. return false;
  2230. //We should exclude model.contextType == VFXContextType.Event of this condition.
  2231. //If VFXConvertSubgraph.TransferContextsFlowEdges has been fixed & renabled.
  2232. if (allDatasHash.Contains(model.GetData()) && !selectedContextUIs.Contains(context))
  2233. return false;
  2234. }
  2235. return true;
  2236. }
  2237. void ToSubgraphBlock(DropdownMenuAction a)
  2238. {
  2239. VFXConvertSubgraph.ConvertToSubgraphBlock(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
  2240. }
  2241. void ToSubgraphOperator(DropdownMenuAction a)
  2242. {
  2243. VFXConvertSubgraph.ConvertToSubgraphOperator(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
  2244. }
  2245. void ToSubgraphContext(DropdownMenuAction a)
  2246. {
  2247. VFXConvertSubgraph.ConvertToSubgraphContext(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
  2248. }
  2249. List<VFXSystemBorder> m_Systems = new List<VFXSystemBorder>();
  2250. public ReadOnlyCollection<VFXSystemBorder> systems
  2251. {
  2252. get { return m_Systems.AsReadOnly(); }
  2253. }
  2254. public void UpdateSystemNames()
  2255. {
  2256. if (m_Systems != null)
  2257. foreach (var system in m_Systems)
  2258. {
  2259. system.Update();
  2260. }
  2261. }
  2262. public void UpdateSystems()
  2263. {
  2264. while (m_Systems.Count() > controller.systems.Count())
  2265. {
  2266. VFXSystemBorder border = m_Systems.Last();
  2267. m_Systems.RemoveAt(m_Systems.Count - 1);
  2268. border.RemoveFromHierarchy();
  2269. }
  2270. UpdateSystemNames();
  2271. while (m_Systems.Count() < controller.systems.Count())
  2272. {
  2273. VFXSystemBorder border = new VFXSystemBorder();
  2274. m_Systems.Add(border);
  2275. AddElement(border);
  2276. border.controller = controller.systems[m_Systems.Count() - 1];
  2277. }
  2278. foreach (var context in GetAllContexts())
  2279. {
  2280. context.UpdateLabel();
  2281. }
  2282. }
  2283. void OnDragUpdated(DragUpdatedEvent e)
  2284. {
  2285. if (controller == null || !IsAssetEditable())
  2286. return;
  2287. if (DragAndDrop.GetGenericData("DragSelection") != null && selection.Any(t => t is VFXBlackboardField && (t as VFXBlackboardField).GetFirstAncestorOfType<VFXBlackboardRow>() != null))
  2288. {
  2289. VFXBlackboardField selectedField = selection.OfType<VFXBlackboardField>().Where(t => t.GetFirstAncestorOfType<VFXBlackboardRow>() != null).First();
  2290. if (selectedField.controller.isOutput && selectedField.controller.nodeCount > 0)
  2291. {
  2292. return;
  2293. }
  2294. DragAndDrop.visualMode = DragAndDropVisualMode.Link;
  2295. e.StopPropagation();
  2296. }
  2297. else
  2298. {
  2299. var references = DragAndDrop.objectReferences.OfType<VisualEffectAsset>().Cast<VisualEffectObject>().Concat(DragAndDrop.objectReferences.OfType<VisualEffectSubgraphOperator>());
  2300. VisualEffectObject draggedObject = references.FirstOrDefault();
  2301. bool isOperator = draggedObject is VisualEffectSubgraphOperator;
  2302. if (draggedObject != null && draggedObject != controller.model.visualEffectObject)
  2303. {
  2304. var draggedObjectDependencies = draggedObject.GetResource().GetOrCreateGraph().subgraphDependencies;
  2305. bool vfxIntovfx = !isOperator && !controller.model.isSubgraph && !draggedObjectDependencies.Contains(controller.model.subgraph); // dropping a vfx into a vfx
  2306. bool operatorIntovfx = isOperator && !controller.model.isSubgraph; //dropping an operator into a vfx
  2307. bool operatorIntoOperator = isOperator && controller.model.visualEffectObject is VisualEffectSubgraphOperator && !draggedObjectDependencies.Contains(controller.model.visualEffectObject); //dropping an operator into a vfx
  2308. if (vfxIntovfx || operatorIntovfx || operatorIntoOperator)
  2309. {
  2310. DragAndDrop.visualMode = DragAndDropVisualMode.Link;
  2311. e.StopPropagation();
  2312. }
  2313. return;
  2314. }
  2315. var droppedBlocks = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>();
  2316. if (droppedBlocks.Count() > 0 && !controller.model.isSubgraph)
  2317. {
  2318. DragAndDrop.visualMode = DragAndDropVisualMode.Link;
  2319. e.StopPropagation();
  2320. }
  2321. }
  2322. }
  2323. void OnDragPerform(DragPerformEvent e)
  2324. {
  2325. if (controller == null || !IsAssetEditable())
  2326. return;
  2327. var groupNode = GetPickedGroupNode(e.mousePosition);
  2328. if (DragAndDrop.GetGenericData("DragSelection") != null && selection.Any(t => t is BlackboardField && (t as BlackboardField).GetFirstAncestorOfType<VFXBlackboardRow>() != null))
  2329. {
  2330. var rows = selection.OfType<BlackboardField>().Select(t => t.GetFirstAncestorOfType<VFXBlackboardRow>()).Where(t => t != null).ToArray();
  2331. if (rows.Length > 0)
  2332. {
  2333. DragAndDrop.AcceptDrag();
  2334. Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
  2335. UpdateSelectionWithNewNode();
  2336. float cpt = 0;
  2337. foreach (var row in rows)
  2338. {
  2339. AddVFXParameter(mousePosition - new Vector2(50, 20) + cpt * new Vector2(0, 40), row.controller, groupNode);
  2340. ++cpt;
  2341. }
  2342. e.StopPropagation();
  2343. }
  2344. }
  2345. else
  2346. {
  2347. DragAndDrop.AcceptDrag();
  2348. var references = DragAndDrop.objectReferences.OfType<VisualEffectAsset>().Cast<VisualEffectObject>().Concat(DragAndDrop.objectReferences.OfType<VisualEffectSubgraphOperator>());
  2349. VisualEffectObject draggedObject = references.FirstOrDefault();
  2350. bool isOperator = draggedObject is VisualEffectSubgraphOperator;
  2351. if (draggedObject != null && draggedObject != controller.model.visualEffectObject)
  2352. {
  2353. var draggedObjectDependencies = draggedObject.GetResource().GetOrCreateGraph().subgraphDependencies;
  2354. bool vfxIntovfx = !isOperator && !controller.model.isSubgraph && !draggedObjectDependencies.Contains(controller.model.subgraph); // dropping a vfx into a vfx
  2355. bool operatorIntovfx = isOperator && !controller.model.isSubgraph; //dropping an operator into a vfx
  2356. bool operatorIntoOperator = isOperator && controller.model.visualEffectObject is VisualEffectSubgraphOperator && !draggedObjectDependencies.Contains(controller.model.visualEffectObject); //dropping an operator into a vfx
  2357. if (vfxIntovfx || operatorIntovfx || operatorIntoOperator)
  2358. {
  2359. Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
  2360. VFXModel newModel = (references.First() is VisualEffectAsset) ? VFXSubgraphContext.CreateInstance<VFXSubgraphContext>() as VFXModel : VFXSubgraphOperator.CreateInstance<VFXSubgraphOperator>() as VFXModel;
  2361. UpdateSelectionWithNewNode();
  2362. controller.AddVFXModel(mousePosition, newModel);
  2363. newModel.SetSettingValue("m_Subgraph", references.First());
  2364. //TODO add to picked groupnode
  2365. e.StopPropagation();
  2366. }
  2367. }
  2368. else if (!controller.model.isSubgraph) //can't drag a vfx subgraph block in a subgraph operator or a subgraph block
  2369. {
  2370. var droppedBlocks = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>();
  2371. VisualEffectSubgraphBlock droppedBlock = droppedBlocks.FirstOrDefault();
  2372. if (droppedBlock != null)
  2373. {
  2374. Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
  2375. VFXContextType contextKind = droppedBlocks.First().GetResource().GetOrCreateGraph().children.OfType<VFXBlockSubgraphContext>().First().compatibleContextType;
  2376. VFXModelDescriptor<VFXContext> contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicInitialize));
  2377. if ((contextKind & VFXContextType.Update) == VFXContextType.Update)
  2378. contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicUpdate));
  2379. else if ((contextKind & VFXContextType.Spawner) == VFXContextType.Spawner)
  2380. contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicSpawner));
  2381. else if ((contextKind & VFXContextType.Output) == VFXContextType.Output)
  2382. contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXPlanarPrimitiveOutput) && t.model.taskType == VFXTaskType.ParticleQuadOutput);
  2383. UpdateSelectionWithNewNode();
  2384. VFXContext ctx = controller.AddVFXContext(mousePosition, contextType);
  2385. VFXModel newModel = VFXSubgraphBlock.CreateInstance<VFXSubgraphBlock>();
  2386. newModel.SetSettingValue("m_Subgraph", droppedBlocks.First());
  2387. UpdateSelectionWithNewNode();
  2388. ctx.AddChild(newModel);
  2389. //TODO add to picked groupnode
  2390. e.StopPropagation();
  2391. }
  2392. }
  2393. }
  2394. }
  2395. public void AssetMoved()
  2396. {
  2397. foreach (var item in this.Query<VFXNodeUI>().ToList())
  2398. {
  2399. item.AssetMoved();
  2400. }
  2401. }
  2402. VFXEdgeDragInfo m_EdgeDragInfo;
  2403. public void StartEdgeDragInfo(VFXDataAnchor draggerAnchor, VFXDataAnchor overAnchor)
  2404. {
  2405. if (m_EdgeDragInfo == null)
  2406. {
  2407. m_EdgeDragInfo = new VFXEdgeDragInfo(this);
  2408. Add(m_EdgeDragInfo);
  2409. m_EdgeDragInfo.style.display = DisplayStyle.None;
  2410. }
  2411. m_EdgeDragInfo.StartEdgeDragInfo(draggerAnchor, overAnchor);
  2412. }
  2413. public void StopEdgeDragInfo()
  2414. {
  2415. if (m_EdgeDragInfo != null)
  2416. m_EdgeDragInfo.StopEdgeDragInfo();
  2417. }
  2418. public void DuplicateBlackboardFieldSelection()
  2419. {
  2420. foreach (var blackboardField in selection.OfType<VFXBlackboardField>())
  2421. {
  2422. DuplicateBlackboardField(blackboardField);
  2423. }
  2424. m_Controller.graph.SetExpressionValueDirty();
  2425. }
  2426. private void DuplicateBlackBoardCategorySelection()
  2427. {
  2428. foreach (var blackboardCategory in selection.OfType<VFXBlackboardCategory>())
  2429. {
  2430. var newCategory = blackboard.AddCategory(blackboardCategory.title);
  2431. var parameters = blackboardCategory
  2432. .Children()
  2433. .OfType<VFXBlackboardRow>()
  2434. .Select(x => DuplicateBlackboardField(x.field))
  2435. .ToList();
  2436. parameters.ForEach(x => x.model.category = newCategory.title);
  2437. newCategory.SyncParameters(new HashSet<VFXParameterController>(parameters));
  2438. }
  2439. }
  2440. private VFXParameterController DuplicateBlackboardField(VFXBlackboardField blackboardField)
  2441. {
  2442. var copyName = blackboardField.controller.MakeNameUnique(blackboardField.controller.exposedName);
  2443. var newVfxParameter = VFXParameter.Duplicate(copyName, blackboardField.controller.model);
  2444. controller.AddVFXModel(Vector2.zero, newVfxParameter);
  2445. bool groupChanged = false;
  2446. controller.SyncControllerFromModel(ref groupChanged);
  2447. var newParameterController = blackboard.controller.parameterControllers.Single(x => x.model == newVfxParameter);
  2448. if (blackboardField.controller.spaceableAndMasterOfSpace)
  2449. {
  2450. newParameterController.space = blackboardField.controller.space;
  2451. }
  2452. return newParameterController;
  2453. }
  2454. }
  2455. }