12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873 |
- using System;
- using System.Collections;
- using System.Collections.ObjectModel;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using UnityEditor.Experimental.GraphView;
- using UnityEditor.Toolbars;
- using UnityEditor.VersionControl;
- using UnityEngine;
- using UnityEngine.VFX;
- using UnityEngine.UIElements;
- using UnityEditor.UIElements;
- using UnityEngine.Profiling;
- using PositionType = UnityEngine.UIElements.Position;
- using Task = UnityEditor.VersionControl.Task;
- namespace UnityEditor.VFX.UI
- {
- /// <summary>
- /// Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor.
- /// </summary>
- [Obsolete("Unexpected public API VFXViewModicationProcessor : Use a custom UnityEditor.AssetModificationProcessor")]
- public class VFXViewModicationProcessor : UnityEditor.AssetModificationProcessor
- {
- /// <summary>
- /// Initialized to false by default.
- /// Obsolete API : Use a custom UnityEditor.AssetModificationProcessor and implement OnWillMoveAsset if you relied on this behavior.
- /// </summary>
- public static bool assetMoved = false;
- }
- class VFXViewModificationProcessor : UnityEditor.AssetModificationProcessor
- {
- public static bool assetMoved = false;
- private static AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
- {
- assetMoved = true;
- return AssetMoveResult.DidNotMove;
- }
- }
- class EdgeDragInfo : VisualElement
- {
- VFXView m_View;
- public EdgeDragInfo(VFXView view)
- {
- m_View = view;
- var tpl = Resources.Load<VisualTreeAsset>("uxml/EdgeDragInfo");
- tpl.CloneTree(this);
- this.AddStyleSheetPath("EdgeDragInfo");
- m_Text = this.Q<Label>("title");
- pickingMode = PickingMode.Ignore;
- m_Text.pickingMode = PickingMode.Ignore;
- }
- Label m_Text;
- public void StartEdgeDragInfo(VFXDataAnchor draggedAnchor, VFXDataAnchor overAnchor)
- {
- string error = null;
- if (draggedAnchor != overAnchor)
- {
- if (draggedAnchor.direction == overAnchor.direction)
- {
- if (draggedAnchor.direction == Direction.Input)
- error = "You must link an input to an output";
- else
- error = "You must link an output to an input";
- }
- else if (draggedAnchor.controller.connections.Any(t => draggedAnchor.direction == Direction.Input ? t.output == overAnchor.controller : t.input == overAnchor.controller))
- {
- error = "An edge with the same input and output already exists";
- }
- else if (!draggedAnchor.controller.model.CanLink(overAnchor.controller.model))
- {
- error = "The input and output have incompatible types";
- }
- else
- {
- bool can = draggedAnchor.controller.CanLink(overAnchor.controller);
- if (!can)
- {
- if (!draggedAnchor.controller.CanLinkToNode(overAnchor.controller.sourceNode, null))
- error = "The edge would create a loop in the operators";
- else
- error = "Link impossible for an unknown reason";
- }
- }
- }
- if (error == null)
- style.display = DisplayStyle.None;
- else
- m_Text.text = error;
- var layout = overAnchor.connector.parent.ChangeCoordinatesTo(m_View, overAnchor.connector.layout);
- style.top = layout.yMax + 16;
- style.left = layout.xMax;
- }
- }
- struct VFXViewSettings
- {
- private bool m_IsAttachedLocked;
- private VisualEffect m_AttachedVisualEffect;
- public void Load(bool force = false)
- {
- m_IsAttachedLocked = EditorPrefs.GetBool(nameof(m_IsAttachedLocked));
- if (EditorApplication.isPlaying || force)
- {
- var attachedVisualEffectPath = EditorPrefs.GetString(nameof(m_AttachedVisualEffect));
- if (!string.IsNullOrEmpty(attachedVisualEffectPath))
- {
- var go = GameObject.Find(attachedVisualEffectPath);
- if (go != null)
- {
- m_AttachedVisualEffect = go.GetComponent<VisualEffect>();
- }
- }
- }
- }
- public VisualEffect AttachedVisualEffect
- {
- get => m_AttachedVisualEffect;
- set
- {
- m_AttachedVisualEffect = value;
- if (!EditorApplication.isPlaying)
- {
- if (m_AttachedVisualEffect != null)
- {
- var go = m_AttachedVisualEffect.gameObject;
- var path = go.GetComponentsInParent<UnityEngine.Transform>()
- .Select(x => x.name)
- .Reverse()
- .ToArray();
- EditorPrefs.SetString(nameof(m_AttachedVisualEffect), "/" + string.Join('/', path));
- }
- else
- {
- EditorPrefs.SetString(nameof(m_AttachedVisualEffect), null);
- }
- }
- }
- }
- public bool AttachedLocked
- {
- get => m_IsAttachedLocked;
- set
- {
- m_IsAttachedLocked = value;
- EditorPrefs.SetBool(nameof(m_IsAttachedLocked), m_IsAttachedLocked);
- }
- }
- }
- class VFXView : GraphView, IControlledElement<VFXViewController>, IControllerListener, IDisposable
- {
- private const int MaximumNameLengthInNotification = 128;
- internal static class Contents
- {
- public static readonly GUIContent attach = EditorGUIUtility.TrTextContent("Attach");
- public static readonly GUIContent detach = EditorGUIUtility.TrTextContent("Detach");
- public static readonly GUIContent clickToUnlock = EditorGUIUtility.TrTextContent("Click to enable auto-attachment to selection");
- public static readonly GUIContent clickToLock = EditorGUIUtility.TrTextContent("Click to disable auto-attachment to selection");
- public static readonly GUIContent noSelection = EditorGUIUtility.TrTextContent("No selection");
- public static readonly GUIContent attachedToGameObject = EditorGUIUtility.TrTextContent("Attached to {0}");
- public static readonly GUIContent notAttached = EditorGUIUtility.TrTextContent("Select a Game Object running this VFX to attach it");
- }
- public HashSet<VFXEditableDataAnchor> allDataAnchors = new HashSet<VFXEditableDataAnchor>();
- public bool locked => m_VFXSettings.AttachedLocked;
- void IControllerListener.OnControllerEvent(ControllerEvent e)
- {
- if (e is VFXRecompileEvent)
- {
- var recompileEvent = e as VFXRecompileEvent;
- foreach (var anchor in allDataAnchors)
- {
- anchor.OnRecompile(recompileEvent.valueOnly);
- }
- }
- }
- VFXViewSettings m_VFXSettings;
- VisualElement m_NoAssetLabel;
- VisualElement m_LockedElement;
- VFXViewController m_Controller;
- Controller IControlledElement.controller
- {
- get { return m_Controller; }
- }
- public Button checkoutButton;
- void DisconnectController()
- {
- if (controller.model && controller.graph)
- controller.graph.SetCompilationMode(VFXViewPreference.forceEditionCompilation ? VFXCompilationMode.Edition : VFXCompilationMode.Runtime);
- m_Controller.UnregisterHandler(this);
- m_Controller.useCount--;
- serializeGraphElements = null;
- unserializeAndPaste = null;
- deleteSelection = null;
- nodeCreationRequest = null;
- elementsAddedToGroup = null;
- elementsRemovedFromGroup = null;
- groupTitleChanged = null;
- m_GeometrySet = false;
- // Remove all in view now that the controller has been disconnected.
- foreach (var element in rootGroupNodeElements.Values)
- {
- RemoveElement(element);
- }
- foreach (var element in groupNodes.Values)
- {
- RemoveElement(element);
- }
- foreach (var element in dataEdges.Values)
- {
- RemoveElement(element);
- }
- foreach (var element in flowEdges.Values)
- {
- RemoveElement(element);
- }
- foreach (var system in m_Systems)
- {
- RemoveElement(system);
- }
- groupNodes.Clear();
- stickyNotes.Clear();
- rootNodes.Clear();
- rootGroupNodeElements.Clear();
- m_Systems.Clear();
- VFXExpression.ClearCache();
- m_NodeProvider = null;
- if (m_Controller.graph)
- {
- m_Controller.graph.errorManager.onClearAllErrors -= ClearAllErrors;
- m_Controller.graph.errorManager.onRegisterError -= RegisterError;
- }
- }
- void ConnectController()
- {
- schedule.Execute(() =>
- {
- if (controller != null && controller.graph)
- controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
- }).ExecuteLater(1);
- if (m_Controller.graph)
- {
- m_Controller.graph.errorManager.onClearAllErrors += ClearAllErrors;
- m_Controller.graph.errorManager.onRegisterError += RegisterError;
- }
- m_Controller.RegisterHandler(this);
- m_Controller.useCount++;
- serializeGraphElements = SerializeElements;
- unserializeAndPaste = UnserializeAndPasteElements;
- deleteSelection = Delete;
- nodeCreationRequest = OnCreateNode;
- elementsAddedToGroup = ElementAddedToGroupNode;
- elementsRemovedFromGroup = ElementRemovedFromGroupNode;
- groupTitleChanged = GroupNodeTitleChanged;
- m_NodeProvider = new VFXNodeProvider(controller, (d, mPos) => AddNode(d, mPos), null, GetAcceptedTypeNodes());
- //Make sure a subgraph block as a block subgraph context
- if (controller.model.isSubgraph && controller.model.subgraph is VisualEffectSubgraphBlock)
- {
- if (!controller.graph.children.Any(t => t is VFXBlockSubgraphContext))
- {
- controller.graph.AddChild(VFXBlockSubgraphContext.CreateInstance<VFXBlockSubgraphContext>(), 0);
- }
- }
- }
- IEnumerable<Type> GetAcceptedTypeNodes()
- {
- if (!controller.model.isSubgraph)
- return null;
- return new Type[] { typeof(VFXOperator) };
- }
- public VisualEffect attachedComponent
- {
- get
- {
- return m_ComponentBoard.GetAttachedComponent();
- }
- set
- {
- if (value == null)
- m_ComponentBoard.Detach();
- else
- m_ComponentBoard.Attach(value);
- }
- }
- public void RemoveAnchorEdges(VFXDataAnchor anchor)
- {
- foreach (var edge in dataEdges.Where(t => t.Value.input == anchor || t.Value.output == anchor).ToArray())
- {
- if (edge.Value.input == anchor)
- edge.Value.output.Disconnect(edge.Value);
- else
- edge.Value.input.Disconnect(edge.Value);
- RemoveElement(edge.Value);
- dataEdges.Remove(edge.Key);
- }
- }
- public void RemoveNodeEdges(VFXNodeUI node)
- {
- foreach (var edge in dataEdges.Where(t => t.Value.input.node == node || t.Value.output.node == node).ToArray())
- {
- RemoveElement(edge.Value);
- dataEdges.Remove(edge.Key);
- }
- }
- public VFXViewController controller
- {
- get { return m_Controller; }
- set
- {
- if (m_Controller != value)
- {
- if (m_Controller != null)
- {
- DisconnectController();
- }
- m_Controller = value;
- if (m_Controller != null)
- {
- ConnectController();
- }
- NewControllerSet();
- AttachToSelection();
- m_ComponentBoard.ResetPlayRate();
- }
- }
- }
- public VFXGroupNode GetPickedGroupNode(Vector2 panelPosition)
- {
- List<VisualElement> picked = new List<VisualElement>();
- panel.PickAll(panelPosition, picked);
- return picked.OfType<VFXGroupNode>().FirstOrDefault();
- }
- public VFXNodeController AddNode(VFXNodeProvider.Descriptor d, Vector2 mPos)
- {
- UpdateSelectionWithNewNode();
- var groupNode = GetPickedGroupNode(mPos);
- mPos = this.ChangeCoordinatesTo(contentViewContainer, mPos);
- if (d.modelDescriptor is string)
- {
- string path = d.modelDescriptor as string;
- if (path.StartsWith(VisualEffectAssetEditorUtility.templatePath) || ((VFXResources.defaultResources.userTemplateDirectory.Length > 0) && path.StartsWith(VFXResources.defaultResources.userTemplateDirectory)))
- CreateTemplateSystem(path, mPos, groupNode);
- else
- {
- if (Path.GetExtension(path) == VisualEffectSubgraphOperator.Extension)
- {
- var subGraph = AssetDatabase.LoadAssetAtPath<VisualEffectSubgraphOperator>(path);
- if (subGraph != null && (!controller.model.isSubgraph || !subGraph.GetResource().GetOrCreateGraph().subgraphDependencies.Contains(controller.model.subgraph) && subGraph.GetResource() != controller.model))
- {
- ;
- VFXModel newModel = VFXSubgraphOperator.CreateInstance<VFXSubgraphOperator>() as VFXModel;
- controller.AddVFXModel(mPos, newModel);
- newModel.SetSettingValue("m_Subgraph", subGraph);
- UpdateSelectionWithNewNode();
- controller.LightApplyChanges();
- return controller.GetNewNodeController(newModel);
- }
- }
- }
- }
- else if (d.modelDescriptor is GroupNodeAdder)
- {
- controller.AddGroupNode(mPos);
- }
- else if (d.modelDescriptor is VFXParameterController)
- {
- var parameter = d.modelDescriptor as VFXParameterController;
- UpdateSelectionWithNewNode();
- return controller.AddVFXParameter(mPos, parameter, groupNode != null ? groupNode.controller : null);
- }
- else
- {
- UpdateSelectionWithNewNode();
- return controller.AddNode(mPos, d.modelDescriptor, groupNode != null ? groupNode.controller : null);
- }
- return null;
- }
- readonly VisualElement m_Toolbar;
- readonly ToolbarToggle m_LockToggle;
- readonly EditorToolbarDropdown m_AttachDropDownButton;
- VFXNodeProvider m_NodeProvider;
- ToolbarButton m_SaveButton;
- bool m_IsRuntimeMode;
- bool m_ForceShaderValidation;
- public static StyleSheet LoadStyleSheet(string text)
- {
- string path = string.Format("{0}/uss/{1}.uss", VisualEffectAssetEditorUtility.editorResourcesPath, text);
- return AssetDatabase.LoadAssetAtPath<StyleSheet>(path);
- }
- public static VisualTreeAsset LoadUXML(string text)
- {
- string path = string.Format("{0}/uxml/{1}.uxml", VisualEffectAssetEditorUtility.editorResourcesPath, text);
- return AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(path);
- }
- public static Texture2D LoadImage(string text)
- {
- string path = string.Format("{0}/VFX/{1}.png", VisualEffectAssetEditorUtility.editorResourcesPath, text);
- return AssetDatabase.LoadAssetAtPath<Texture2D>(path);
- }
- SelectionDragger m_SelectionDragger;
- RectangleSelector m_RectangleSelector;
- public void OnCreateAsset()
- {
- string filePath = EditorUtility.SaveFilePanelInProject("", "New Graph", "vfx", "Create new VisualEffect Graph");
- if (!string.IsNullOrEmpty(filePath))
- {
- VisualEffectAssetEditorUtility.CreateTemplateAsset(filePath);
- VFXViewWindow.currentWindow.LoadAsset(AssetDatabase.LoadAssetAtPath<VisualEffectAsset>(filePath), null);
- }
- }
- public VFXView()
- {
- EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
- SetupZoom(0.125f, 8);
- this.AddManipulator(new ContentDragger());
- m_SelectionDragger = new SelectionDragger();
- m_RectangleSelector = new RectangleSelector();
- this.AddManipulator(m_SelectionDragger);
- this.AddManipulator(m_RectangleSelector);
- this.AddManipulator(new FreehandSelector());
- styleSheets.Add(LoadStyleSheet("VFXView"));
- if (!EditorGUIUtility.isProSkin)
- {
- styleSheets.Add(LoadStyleSheet("VFXView-light"));
- }
- else
- {
- styleSheets.Add(LoadStyleSheet("VFXView-dark"));
- }
- AddLayer(-1);
- AddLayer(1);
- AddLayer(2);
- focusable = true;
- m_Toolbar = new UnityEditor.UIElements.Toolbar();
- var toggleAutoCompile = new ToolbarToggle();
- toggleAutoCompile.text = "Auto";
- toggleAutoCompile.style.unityTextAlign = TextAnchor.MiddleRight;
- toggleAutoCompile.SetValueWithoutNotify(true);
- toggleAutoCompile.RegisterCallback<ChangeEvent<bool>>(OnToggleCompile);
- m_Toolbar.Add(toggleAutoCompile);
- var compileButton = new ToolbarButton(OnCompile);
- compileButton.style.unityTextAlign = TextAnchor.MiddleLeft;
- compileButton.text = "Compile";
- m_Toolbar.Add(compileButton);
- var resyncMatButton = new ToolbarButton(OnResyncMaterial);
- resyncMatButton.style.unityTextAlign = TextAnchor.MiddleLeft;
- resyncMatButton.text = "Resync Material";
- m_Toolbar.Add(resyncMatButton);
- m_SaveButton = new ToolbarButton(OnSave);
- m_SaveButton.style.unityTextAlign = TextAnchor.MiddleLeft;
- m_SaveButton.text = "Save";
- m_Toolbar.Add(m_SaveButton);
- m_AttachDropDownButton = new EditorToolbarDropdown(Contents.attach.text, OnOpenAttachMenu);
- m_AttachDropDownButton.name = "attach-toolbar-button";
- m_Toolbar.Add(m_AttachDropDownButton);
- m_LockToggle = new ToolbarToggle();
- m_LockToggle.style.unityTextAlign = TextAnchor.MiddleLeft;
- m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
- m_LockToggle.name = "lock-auto-attach";
- m_LockToggle.RegisterCallback<ChangeEvent<bool>>(OnToggleLock);
- m_Toolbar.Add(m_LockToggle);
- var spacer = new ToolbarSpacer();
- spacer.style.width = 12f;
- m_Toolbar.Add(spacer);
- var selectAssetButton = new ToolbarButton(() => { SelectAsset(); });
- selectAssetButton.text = "Show in Project";
- m_Toolbar.Add(selectAssetButton);
- spacer = new ToolbarSpacer();
- spacer.style.width = 10;
- m_Toolbar.Add(spacer);
- checkoutButton = new ToolbarButton(() => { Checkout(); });
- checkoutButton.text = "Check Out";
- checkoutButton.visible = false;
- checkoutButton.AddToClassList("toolbarItem");
- m_Toolbar.Add(checkoutButton);
- var flexSpacer = new ToolbarSpacer();
- flexSpacer.style.flexGrow = 1f;
- m_Toolbar.Add(flexSpacer);
- var toggleBlackboard = new ToolbarToggle();
- toggleBlackboard.text = "Blackboard";
- toggleBlackboard.RegisterCallback<ChangeEvent<bool>>(ToggleBlackboard);
- m_Toolbar.Add(toggleBlackboard);
- m_ToggleComponentBoard = new ToolbarToggle();
- m_ToggleComponentBoard.text = "Control";
- m_ToggleComponentBoard.RegisterCallback<ChangeEvent<bool>>(ToggleComponentBoard);
- m_Toolbar.Add(m_ToggleComponentBoard);
- var showDebugMenu = new ToolbarMenu();
- showDebugMenu.text = "Advanced";
- showDebugMenu.menu.AppendAction("Runtime Mode (Forced)", OnRuntimeModeChanged, RuntimeModeStatus);
- showDebugMenu.menu.AppendAction("Shader Validation (Forced)", OnShaderValidationChanged, ShaderValidationStatus);
- showDebugMenu.menu.AppendSeparator();
- showDebugMenu.menu.AppendAction("Refresh UI", OnRefreshUI, DropdownMenuAction.Status.Normal);
- m_Toolbar.Add(showDebugMenu);
- // End Toolbar
- 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" };
- m_NoAssetLabel.style.position = PositionType.Absolute;
- m_NoAssetLabel.style.left = new StyleLength(40f);
- m_NoAssetLabel.style.right = new StyleLength(40f);
- m_NoAssetLabel.style.top = new StyleLength(40f);
- m_NoAssetLabel.style.bottom = new StyleLength(140f);
- m_NoAssetLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
- m_NoAssetLabel.style.fontSize = new StyleLength(12f);
- m_NoAssetLabel.style.color = Color.white * 0.75f;
- Add(m_NoAssetLabel);
- var createButton = new Button() { text = "Create new Visual Effect Graph" };
- m_NoAssetLabel.Add(createButton);
- createButton.clicked += OnCreateAsset;
- m_LockedElement = new Label("Asset is Locked");
- m_LockedElement.style.position = PositionType.Absolute;
- m_LockedElement.style.left = 0f;
- m_LockedElement.style.right = new StyleLength(0f);
- m_LockedElement.style.top = new StyleLength(0f);
- m_LockedElement.style.bottom = new StyleLength(0f);
- m_LockedElement.style.unityTextAlign = TextAnchor.MiddleCenter;
- m_LockedElement.style.fontSize = new StyleLength(72f);
- m_LockedElement.style.color = Color.white * 0.75f;
- m_LockedElement.style.display = DisplayStyle.None;
- m_LockedElement.focusable = true;
- m_LockedElement.RegisterCallback<KeyDownEvent>(e => e.StopPropagation());
- m_Blackboard = new VFXBlackboard(this);
- bool blackboardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.blackboard, true);
- if (blackboardVisible)
- Add(m_Blackboard);
- toggleBlackboard.value = blackboardVisible;
- m_ComponentBoard = new VFXComponentBoard(this);
- #if _ENABLE_RESTORE_BOARD_VISIBILITY
- bool componentBoardVisible = BoardPreferenceHelper.IsVisible(BoardPreferenceHelper.Board.componentBoard, false);
- if (componentBoardVisible)
- ShowComponentBoard();
- toggleComponentBoard.value = componentBoardVisible;
- #endif
- Add(m_LockedElement);
- Add(m_Toolbar);
- m_Toolbar.SetEnabled(false);
- m_VFXSettings = new VFXViewSettings();
- m_VFXSettings.Load();
- m_LockToggle.value = m_VFXSettings.AttachedLocked;
- RegisterCallback<DragUpdatedEvent>(OnDragUpdated);
- RegisterCallback<DragPerformEvent>(OnDragPerform);
- RegisterCallback<ValidateCommandEvent>(ValidateCommand);
- RegisterCallback<ExecuteCommandEvent>(ExecuteCommand);
- RegisterCallback<AttachToPanelEvent>(OnEnterPanel);
- RegisterCallback<DetachFromPanelEvent>(OnLeavePanel);
- RegisterCallback<KeyDownEvent>(OnKeyDownEvent);
- graphViewChanged = VFXGraphViewChanged;
- elementResized = VFXElementResized;
- canPasteSerializedData = VFXCanPaste;
- viewDataKey = "VFXView";
- RegisterCallback<GeometryChangedEvent>(OnFirstResize);
- }
- public void Dispose()
- {
- UnregisterCallback<DragUpdatedEvent>(OnDragUpdated);
- UnregisterCallback<DragPerformEvent>(OnDragPerform);
- UnregisterCallback<ValidateCommandEvent>(ValidateCommand);
- UnregisterCallback<ExecuteCommandEvent>(ExecuteCommand);
- UnregisterCallback<AttachToPanelEvent>(OnEnterPanel);
- UnregisterCallback<DetachFromPanelEvent>(OnLeavePanel);
- UnregisterCallback<KeyDownEvent>(OnKeyDownEvent);
- UnregisterCallback<GeometryChangedEvent>(OnFirstResize);
- EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
- }
- void OnPlayModeStateChanged(PlayModeStateChange playModeState)
- {
- if (playModeState == PlayModeStateChange.EnteredEditMode)
- {
- m_VFXSettings.Load(true);
- TryAttachTo(m_VFXSettings.AttachedVisualEffect);
- }
- }
- void OnOpenAttachMenu()
- {
- var attachPanel = ScriptableObject.CreateInstance<VFXAttachPanel>();
- var bounds = new Rect(ViewToScreenPosition(m_AttachDropDownButton.worldBound.position), m_AttachDropDownButton.worldBound.size);
- bounds.xMin++;
- attachPanel.ShowAsDropDown(bounds, attachPanel.WindowSize, new[] { PopupLocation.BelowAlignLeft });
- }
- void OnRefreshUI(DropdownMenuAction action)
- {
- Resync();
- }
- void OnRuntimeModeChanged(DropdownMenuAction action)
- {
- m_IsRuntimeMode = !m_IsRuntimeMode;
- controller.graph.SetCompilationMode(m_IsRuntimeMode ? VFXCompilationMode.Runtime : VFXCompilationMode.Edition);
- }
- DropdownMenuAction.Status RuntimeModeStatus(DropdownMenuAction action)
- {
- if (m_IsRuntimeMode)
- return DropdownMenuAction.Status.Checked;
- else
- return DropdownMenuAction.Status.Normal;
- }
- void OnShaderValidationChanged(DropdownMenuAction action)
- {
- m_ForceShaderValidation = !m_ForceShaderValidation;
- controller.graph.SetForceShaderValidation(m_ForceShaderValidation);
- }
- DropdownMenuAction.Status ShaderValidationStatus(DropdownMenuAction action)
- {
- if (m_ForceShaderValidation)
- return DropdownMenuAction.Status.Checked;
- else
- return DropdownMenuAction.Status.Normal;
- }
- [NonSerialized]
- Dictionary<VFXModel, List<IconBadge>> m_InvalidateBadges = new Dictionary<VFXModel, List<IconBadge>>();
- [NonSerialized]
- List<IconBadge> m_CompileBadges = new List<IconBadge>();
- private void RegisterError(VFXModel model, VFXErrorOrigin errorOrigin, string error, VFXErrorType type, string description)
- {
- VisualElement target = null;
- VisualElement targetParent = null;
- SpriteAlignment alignement = SpriteAlignment.TopLeft;
- if (model is VFXSlot)
- {
- var slot = (VFXSlot)model;
- // todo manage parameter slot if they can have error
- var nodeController = controller.GetNodeController(slot.owner as VFXModel, 0);
- if (nodeController == null)
- return;
- var anchorController = (slot.direction == VFXSlot.Direction.kInput ? nodeController.inputPorts : nodeController.outputPorts).FirstOrDefault(t => t.model == slot);
- if (anchorController == null)
- return;
- targetParent = GetNodeByController(nodeController);
- target = (targetParent as VFXNodeUI).GetPorts(slot.direction == VFXSlot.Direction.kInput, slot.direction != VFXSlot.Direction.kInput).FirstOrDefault(t => t.controller == anchorController);
- alignement = slot.direction == VFXSlot.Direction.kInput ? SpriteAlignment.LeftCenter : SpriteAlignment.RightCenter;
- }
- else if (model is IVFXSlotContainer)
- {
- var node = model;
- var nodeController = controller.GetNodeController(node, 0);
- if (nodeController == null)
- return;
- target = GetNodeByController(nodeController);
- if (target == null)
- return;
- if (nodeController is VFXBlockController blkController)
- {
- VFXNodeUI targetContext = GetNodeByController(blkController.contextController);
- if (targetContext == null)
- return;
- targetParent = targetContext.parent;
- }
- else
- {
- targetParent = target.parent;
- }
- target = (target as VFXNodeUI).titleContainer;
- alignement = SpriteAlignment.LeftCenter;
- }
- if (target != null && targetParent != null)
- {
- var badge = type == VFXErrorType.Error ? IconBadge.CreateError(description) : IconBadge.CreateComment(description);
- targetParent.Add(badge);
- badge.AttachTo(target, alignement);
- if (errorOrigin == VFXErrorOrigin.Compilation)
- {
- m_CompileBadges.Add(badge);
- }
- else
- {
- List<IconBadge> badges;
- if (!m_InvalidateBadges.TryGetValue(model, out badges))
- {
- badges = new List<IconBadge>();
- m_InvalidateBadges[model] = badges;
- }
- badges.Add(badge);
- }
- badge.AddManipulator(new Clickable(() =>
- {
- badge.Detach();
- badge.RemoveFromHierarchy();
- }));
- badge.AddManipulator(new DownClickable(() =>
- {
- GenericMenu menu = new GenericMenu();
- menu.AddItem(EditorGUIUtility.TrTextContent("Hide"), false, () =>
- {
- badge.Detach();
- badge.RemoveFromHierarchy();
- });
- if (type != VFXErrorType.Error)
- {
- menu.AddItem(EditorGUIUtility.TrTextContent("Ignore"), false, () =>
- {
- badge.Detach();
- badge.RemoveFromHierarchy();
- model.IgnoreError(error);
- });
- }
- menu.ShowAsContext();
- }
- ));
- }
- }
- private void ClearAllErrors(VFXModel model, VFXErrorOrigin errorOrigin)
- {
- if (errorOrigin == VFXErrorOrigin.Compilation)
- {
- foreach (var badge in m_CompileBadges)
- {
- badge.Detach();
- badge.RemoveFromHierarchy();
- }
- m_CompileBadges.Clear();
- }
- else
- {
- if (!object.ReferenceEquals(model, null))
- {
- List<IconBadge> badges;
- if (m_InvalidateBadges.TryGetValue(model, out badges))
- {
- foreach (var badge in badges)
- {
- badge.Detach();
- badge.RemoveFromHierarchy();
- }
- m_InvalidateBadges.Remove(model);
- }
- }
- else
- throw new InvalidOperationException("Can't clear in Invalidate mode without a model");
- }
- }
- public void SetBoardToFront(GraphElement board)
- {
- board.SendToBack();
- board.PlaceBehind(m_Toolbar);
- }
- public void AttachToSelection()
- {
- var vfxWindow = VFXViewWindow.currentWindow;
- if (TryAttachTo((Selection.activeObject as GameObject)?.GetComponent<VisualEffect>()) && vfxWindow != null)
- {
- string truncatedObjectName = TruncateName(Selection.activeObject.name, MaximumNameLengthInNotification);
- vfxWindow.ShowNotification(new GUIContent($"Attached to {truncatedObjectName}"), 1.5);
- vfxWindow.Repaint();
- }
- }
- public bool TryAttachTo(VisualEffect selectedAsset)
- {
- bool attached = false;
- if (selectedAsset != null && controller?.graph.visualEffectResource.asset == selectedAsset.visualEffectAsset)
- {
- attached = m_ComponentBoard.Attach(selectedAsset);
- }
- m_VFXSettings.AttachedVisualEffect = attached ? selectedAsset : null;
- UpdateToolbarButtons();
- return attached;
- }
- internal void Detach()
- {
- m_ComponentBoard.Detach();
- UpdateToolbarButtons();
- }
- public void DetachIfDeleted()
- {
- if (m_ComponentBoard.GetAttachedComponent() == null)
- {
- Detach();
- }
- }
- private void UpdateToolbarButtons()
- {
- if (attachedComponent != null)
- {
- m_AttachDropDownButton.AddToClassList("checked");
- }
- else
- {
- m_AttachDropDownButton.RemoveFromClassList("checked");
- }
- m_LockToggle.tooltip = locked ? Contents.clickToUnlock.text : Contents.clickToLock.text;
- m_AttachDropDownButton.tooltip = attachedComponent != null && !string.IsNullOrEmpty(attachedComponent.name)
- ? string.Format(Contents.attachedToGameObject.text, TruncateName(attachedComponent.name, MaximumNameLengthInNotification))
- : Contents.notAttached.text;
- }
- string TruncateName(string nameToTruncate, int maxLength)
- {
- return nameToTruncate.Length > maxLength
- ? nameToTruncate.Substring(0, maxLength) + "..."
- : nameToTruncate;
- }
- void OnUndoPerformed()
- {
- foreach (var anchor in allDataAnchors)
- {
- anchor.ForceUpdate();
- }
- this.m_Blackboard.ForceUpdate();
- }
- void OnToggleLock(ChangeEvent<bool> evt)
- {
- m_VFXSettings.AttachedLocked = !locked;
- if (!locked)
- {
- AttachToSelection();
- }
- else
- {
- UpdateToolbarButtons();
- }
- }
- void ToggleBlackboard(ChangeEvent<bool> e)
- {
- if (m_Blackboard.parent == null)
- {
- Insert(childCount - 1, m_Blackboard);
- BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.blackboard, true);
- m_Blackboard.RegisterCallback<GeometryChangedEvent>(OnFirstBlackboardGeometryChanged);
- m_Blackboard.style.position = PositionType.Absolute;
- }
- else
- {
- m_Blackboard.RemoveFromHierarchy();
- BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.blackboard, false);
- }
- }
- void ToggleComponentBoard()
- {
- if (m_ComponentBoard.parent == null)
- {
- Insert(childCount - 1, m_ComponentBoard);
- BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.componentBoard, true);
- m_ComponentBoard.RegisterCallback<GeometryChangedEvent>(OnFirstComponentBoardGeometryChanged);
- }
- else
- {
- m_ComponentBoard.RemoveFromHierarchy();
- BoardPreferenceHelper.SetVisible(BoardPreferenceHelper.Board.componentBoard, false);
- }
- m_ComponentBoard.RefreshInitializeErrors();
- }
- void OnFirstComponentBoardGeometryChanged(GeometryChangedEvent e)
- {
- if (m_FirstResize)
- {
- m_ComponentBoard.ValidatePosition();
- m_ComponentBoard.UnregisterCallback<GeometryChangedEvent>(OnFirstComponentBoardGeometryChanged);
- }
- }
- void OnFirstBlackboardGeometryChanged(GeometryChangedEvent e)
- {
- if (m_FirstResize)
- {
- m_Blackboard.ValidatePosition();
- m_Blackboard.UnregisterCallback<GeometryChangedEvent>(OnFirstBlackboardGeometryChanged);
- }
- }
- public bool m_FirstResize = false;
- void OnFirstResize(GeometryChangedEvent e)
- {
- m_FirstResize = true;
- m_ComponentBoard.ValidatePosition();
- m_Blackboard.ValidatePosition();
- UnregisterCallback<GeometryChangedEvent>(OnFirstResize);
- }
- Toggle m_ToggleComponentBoard;
- void ToggleComponentBoard(ChangeEvent<bool> e)
- {
- ToggleComponentBoard();
- }
- public void OnVisualEffectComponentChanged(IEnumerable<VisualEffect> visualEffects)
- {
- m_ComponentBoard.OnVisualEffectComponentChanged(visualEffects);
- }
- void Delete(string cmd, AskUser askUser)
- {
- var currentSelection = selection.ToArray();
- var parametersToRemove = Enumerable.Empty<VFXParameterController>();
- foreach (var category in currentSelection.OfType<VFXBlackboardCategory>())
- {
- parametersToRemove = parametersToRemove.Concat(controller.RemoveCategory(m_Blackboard.GetCategoryIndex(category)));
- }
- controller.Remove(currentSelection.OfType<IControlledElement>().Select(t => t.controller).Concat(parametersToRemove.Cast<Controller>()), true);
- }
- void IControlledElement.OnControllerChanged(ref ControllerChangedEvent e)
- {
- if (e.controller == controller)
- {
- ControllerChanged(e.change);
- }
- else if (e.controller is VFXNodeController)
- {
- UpdateUIBounds();
- if (e.controller is VFXContextController && e.target is VFXContextUI)
- {
- m_ComponentBoard.UpdateEventList();
- UpdateSystemNames();
- }
- }
- }
- bool m_InControllerChanged;
- void ControllerChanged(int change)
- {
- if (change == VFXViewController.Change.assetName)
- return;
- m_InControllerChanged = true;
- if (change == VFXViewController.Change.groupNode)
- {
- Profiler.BeginSample("VFXView.SyncGroupNodes");
- SyncGroupNodes();
- Profiler.EndSample();
- var groupNodes = this.groupNodes;
- foreach (var groupNode in groupNodes.Values)
- {
- Profiler.BeginSample("VFXGroupNode.SelfChange");
- groupNode.SelfChange();
- Profiler.EndSample();
- }
- return;
- }
- if (change == VFXViewController.Change.destroy)
- {
- m_Blackboard.controller = null;
- controller = null;
- return;
- }
- Profiler.BeginSample("VFXView.ControllerChanged");
- if (change == VFXViewController.AnyThing)
- {
- SyncNodes();
- }
- Profiler.BeginSample("VFXView.SyncStickyNotes");
- SyncStickyNotes();
- Profiler.EndSample();
- Profiler.BeginSample("VFXView.SyncEdges");
- SyncEdges(change);
- Profiler.EndSample();
- Profiler.BeginSample("VFXView.SyncGroupNodes");
- SyncGroupNodes();
- Profiler.EndSample();
- if (controller != null)
- {
- if (change == VFXViewController.AnyThing)
- {
- // if the asset is destroyed somehow, fox example if the user delete the asset, update the controller and update the window.
- var asset = controller.model;
- if (asset == null)
- {
- this.controller = null;
- return;
- }
- }
- }
- m_InControllerChanged = false;
- if (change != VFXViewController.Change.dataEdge)
- UpdateSystems();
- if (m_UpdateUIBounds)
- {
- Profiler.BeginSample("VFXView.UpdateUIBounds");
- UpdateUIBounds();
- Profiler.EndSample();
- }
- Profiler.EndSample();
- }
- public bool IsAssetEditable()
- {
- return controller.model != null && controller.model.IsAssetEditable();
- }
- void NewControllerSet()
- {
- m_Blackboard.controller = controller;
- m_ComponentBoard.controller = controller;
- if (controller != null)
- {
- m_NoAssetLabel.RemoveFromHierarchy();
- m_Toolbar.SetEnabled(true);
- m_AttachDropDownButton.SetEnabled(this.controller.graph.visualEffectResource.subgraph == null);
- m_LockToggle.SetEnabled(this.controller.graph.visualEffectResource.subgraph == null);
- if (IsAssetEditable())
- {
- m_LockedElement.style.display = DisplayStyle.None;
- m_Blackboard.UnlockUI();
- }
- else
- {
- m_LockedElement.style.display = DisplayStyle.Flex;
- m_Blackboard.LockUI();
- }
- }
- else
- {
- if (m_NoAssetLabel.parent == null)
- {
- Add(m_NoAssetLabel);
- m_Toolbar.SetEnabled(false);
- }
- }
- if (m_VFXSettings.AttachedVisualEffect != null)
- {
- TryAttachTo(m_VFXSettings.AttachedVisualEffect);
- }
- }
- public void OnFocus()
- {
- if (controller != null && controller.model.asset != null && !IsAssetEditable())
- {
- if (m_LockedElement.style.display != DisplayStyle.Flex)
- {
- m_LockedElement.style.display = DisplayStyle.Flex;
- this.RemoveManipulator(m_SelectionDragger);
- this.RemoveManipulator(m_RectangleSelector);
- m_LockedElement.Focus();
- }
- m_Blackboard.LockUI();
- }
- else
- {
- if (m_LockedElement.style.display != DisplayStyle.None)
- {
- m_LockedElement.style.display = DisplayStyle.None;
- this.AddManipulator(m_SelectionDragger);
- this.AddManipulator(m_RectangleSelector);
- }
- m_Blackboard.UnlockUI();
- }
- if (m_Blackboard.parent != null)
- m_LockedElement.PlaceInFront(contentViewContainer);
- }
- public void FrameNewController()
- {
- if (panel != null)
- {
- FrameAfterAWhile();
- }
- else
- {
- RegisterCallback<GeometryChangedEvent>(OnFrameNewControllerWithPanel);
- }
- }
- void FrameAfterAWhile()
- {
- var rectToFit = contentViewContainer.layout;
- var frameTranslation = Vector3.zero;
- var frameScaling = Vector3.one;
- rectToFit = controller.graph.UIInfos.uiBounds;
- if (rectToFit.width <= 50 || rectToFit.height <= 50)
- {
- return;
- }
- Rect rectAvailable = layout;
- float validateFloat = rectAvailable.x + rectAvailable.y + rectAvailable.width + rectAvailable.height;
- if (float.IsInfinity(validateFloat) || float.IsNaN(validateFloat))
- {
- schedule.Execute(FrameAfterAWhile);
- return;
- }
- CalculateFrameTransform(rectToFit, rectAvailable, 30, out frameTranslation, out frameScaling);
- Matrix4x4.TRS(frameTranslation, Quaternion.identity, frameScaling);
- UpdateViewTransform(frameTranslation, frameScaling);
- contentViewContainer.MarkDirtyRepaint();
- }
- bool m_GeometrySet = false;
- void OnFrameNewControllerWithPanel(GeometryChangedEvent e)
- {
- m_GeometrySet = true;
- FrameAfterAWhile();
- UnregisterCallback<GeometryChangedEvent>(OnFrameNewControllerWithPanel);
- }
- Dictionary<VFXNodeController, VFXNodeUI> rootNodes = new Dictionary<VFXNodeController, VFXNodeUI>();
- Dictionary<Controller, GraphElement> rootGroupNodeElements = new Dictionary<Controller, GraphElement>();
- public GraphElement GetGroupNodeElement(Controller controller)
- {
- GraphElement result = null;
- rootGroupNodeElements.TryGetValue(controller, out result);
- return result;
- }
- Dictionary<VFXGroupNodeController, VFXGroupNode> groupNodes = new Dictionary<VFXGroupNodeController, VFXGroupNode>();
- Dictionary<VFXStickyNoteController, VFXStickyNote> stickyNotes = new Dictionary<VFXStickyNoteController, VFXStickyNote>();
- void OnOneNodeGeometryChanged(GeometryChangedEvent e)
- {
- m_GeometrySet = true;
- (e.target as GraphElement).UnregisterCallback<GeometryChangedEvent>(OnOneNodeGeometryChanged);
- }
- bool m_UpdateSelectionWithNewNode;
- public void UpdateSelectionWithNewNode()
- {
- m_UpdateSelectionWithNewNode = true;
- }
- void SyncNodes()
- {
- Profiler.BeginSample("VFXView.SyncNodes");
- if (controller == null)
- {
- foreach (var element in rootNodes.Values.ToArray())
- {
- SafeRemoveElement(element);
- }
- rootNodes.Clear();
- rootGroupNodeElements.Clear();
- }
- else
- {
- elementsAddedToGroup = null;
- elementsRemovedFromGroup = null;
- Profiler.BeginSample("VFXView.SyncNodes:Delete");
- var deletedControllers = rootNodes.Keys.Except(controller.nodes).ToArray();
- foreach (var deletedController in deletedControllers)
- {
- SafeRemoveElement(rootNodes[deletedController]);
- rootNodes.Remove(deletedController);
- rootGroupNodeElements.Remove(deletedController);
- }
- Profiler.EndSample();
- bool needOneListenToGeometry = !m_GeometrySet;
- Profiler.BeginSample("VFXView.SyncNodes:Create");
- bool selectionCleared = false;
- foreach (var newController in controller.nodes.Except(rootNodes.Keys).ToArray())
- {
- VFXNodeUI newElement = null;
- if (newController is VFXContextController)
- {
- newElement = new VFXContextUI();
- }
- else if (newController is VFXOperatorController)
- {
- newElement = new VFXOperatorUI();
- }
- else if (newController is VFXParameterNodeController)
- {
- newElement = new VFXParameterUI();
- }
- else
- {
- throw new InvalidOperationException("Can't find right ui for controller" + newController.GetType().Name);
- }
- Profiler.BeginSample("VFXView.SyncNodes:AddElement");
- FastAddElement(newElement);
- Profiler.EndSample();
- rootNodes[newController] = newElement;
- rootGroupNodeElements[newController] = newElement;
- (newElement as ISettableControlledElement<VFXNodeController>).controller = newController;
- if (needOneListenToGeometry)
- {
- needOneListenToGeometry = false;
- newElement.RegisterCallback<GeometryChangedEvent>(OnOneNodeGeometryChanged);
- }
- newElement.controller.model.RefreshErrors(controller.graph);
- if (m_UpdateSelectionWithNewNode)
- {
- if (!selectionCleared)
- {
- selectionCleared = true;
- ClearSelection();
- }
- AddToSelection(newElement);
- }
- }
- m_UpdateSelectionWithNewNode = false;
- Profiler.EndSample();
- elementsAddedToGroup = ElementAddedToGroupNode;
- elementsRemovedFromGroup = ElementRemovedFromGroupNode;
- }
- Profiler.EndSample();
- }
- static FieldInfo s_Member_ContainerLayer = typeof(GraphView).GetField("m_ContainerLayers", BindingFlags.NonPublic | BindingFlags.Instance);
- static MethodInfo s_Method_GetLayer = typeof(GraphView).GetMethod("GetLayer", BindingFlags.NonPublic | BindingFlags.Instance);
- public void FastAddElement(GraphElement graphElement)
- {
- if (graphElement.IsResizable())
- {
- graphElement.hierarchy.Add(new Resizer());
- graphElement.style.borderBottomWidth = 6;
- }
- int newLayer = graphElement.layer;
- if (!(s_Member_ContainerLayer.GetValue(this) as IDictionary).Contains(newLayer))
- {
- AddLayer(newLayer);
- }
- (s_Method_GetLayer.Invoke(this, new object[] { newLayer }) as VisualElement).Add(graphElement);
- }
- bool m_UpdateUIBounds = false;
- void UpdateUIBounds()
- {
- if (!m_GeometrySet) return;
- if (m_InControllerChanged)
- {
- m_UpdateUIBounds = true;
- return;
- }
- m_UpdateUIBounds = false;
- if (panel != null)
- {
- panel.InternalValidateLayout();
- controller.graph.UIInfos.uiBounds = GetElementsBounds(rootGroupNodeElements.Values.Concat(groupNodes.Values.Cast<GraphElement>()));
- }
- }
- void SyncGroupNodes()
- {
- if (controller == null)
- {
- foreach (var kv in groupNodes)
- {
- RemoveElement(kv.Value);
- }
- groupNodes.Clear();
- }
- else
- {
- var deletedControllers = groupNodes.Keys.Except(controller.groupNodes).ToArray();
- foreach (var deletedController in deletedControllers)
- {
- RemoveElement(groupNodes[deletedController]);
- groupNodes.Remove(deletedController);
- }
- foreach (var newController in controller.groupNodes.Except(groupNodes.Keys))
- {
- var newElement = new VFXGroupNode();
- FastAddElement(newElement);
- newElement.controller = newController;
- groupNodes.Add(newController, newElement);
- }
- }
- }
- void SyncStickyNotes()
- {
- if (controller == null)
- {
- foreach (var kv in stickyNotes)
- {
- SafeRemoveElement(kv.Value);
- }
- rootGroupNodeElements.Clear();
- stickyNotes.Clear();
- }
- else
- {
- var deletedControllers = stickyNotes.Keys.Except(controller.stickyNotes).ToArray();
- foreach (var deletedController in deletedControllers)
- {
- SafeRemoveElement(stickyNotes[deletedController]);
- rootGroupNodeElements.Remove(deletedController);
- stickyNotes.Remove(deletedController);
- }
- foreach (var newController in controller.stickyNotes.Except(stickyNotes.Keys))
- {
- var newElement = new VFXStickyNote();
- newElement.controller = newController;
- FastAddElement(newElement);
- rootGroupNodeElements[newController] = newElement;
- stickyNotes[newController] = newElement;
- }
- }
- }
- public void SafeRemoveElement(GraphElement element)
- {
- VFXGroupNode.inRemoveElement = true;
- RemoveElement(element);
- VFXGroupNode.inRemoveElement = false;
- }
- Dictionary<VFXDataEdgeController, VFXDataEdge> dataEdges = new Dictionary<VFXDataEdgeController, VFXDataEdge>();
- Dictionary<VFXFlowEdgeController, VFXFlowEdge> flowEdges = new Dictionary<VFXFlowEdgeController, VFXFlowEdge>();
- void SyncEdges(int change)
- {
- if (change == VFXViewController.Change.ui)
- return; // for the moment ui changes don't have an impact on edges
- if (change != VFXViewController.Change.flowEdge)
- {
- if (controller == null)
- {
- foreach (var element in dataEdges.Values)
- {
- RemoveElement(element);
- }
- dataEdges.Clear();
- }
- else
- {
- var deletedControllers = dataEdges.Keys.Except(controller.dataEdges).ToArray();
- foreach (var deletedController in deletedControllers)
- {
- var edge = dataEdges[deletedController];
- if (edge.input != null)
- {
- edge.input.Disconnect(edge);
- }
- if (edge.output != null)
- {
- edge.output.Disconnect(edge);
- }
- RemoveElement(edge);
- dataEdges.Remove(deletedController);
- }
- foreach (var newController in controller.dataEdges.Except(dataEdges.Keys).ToArray())
- {
- // 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
- // nodes arrive.
- if (GetNodeByController(newController.input.sourceNode) == null || GetNodeByController(newController.output.sourceNode) == null)
- {
- if (change != VFXViewController.Change.dataEdge)
- {
- Debug.LogError("Can't match nodes for a data edge after nodes should have been updated.");
- }
- continue;
- }
- var newElement = new VFXDataEdge();
- FastAddElement(newElement);
- newElement.controller = newController;
- dataEdges.Add(newController, newElement);
- if (newElement.input != null)
- newElement.input.node.RefreshExpandedState();
- if (newElement.output != null)
- newElement.output.node.RefreshExpandedState();
- }
- }
- }
- if (change != VFXViewController.Change.dataEdge)
- {
- if (controller == null)
- {
- foreach (var element in flowEdges.Values)
- {
- RemoveElement(element);
- }
- flowEdges.Clear();
- }
- else
- {
- var deletedControllers = flowEdges.Keys.Except(controller.flowEdges).ToArray();
- foreach (var deletedController in deletedControllers)
- {
- var edge = flowEdges[deletedController];
- if (edge.input != null)
- {
- edge.input.Disconnect(edge);
- }
- if (edge.output != null)
- {
- edge.output.Disconnect(edge);
- }
- RemoveElement(edge);
- flowEdges.Remove(deletedController);
- }
- foreach (var newController in controller.flowEdges.Except(flowEdges.Keys))
- {
- var newElement = new VFXFlowEdge();
- FastAddElement(newElement);
- newElement.controller = newController;
- flowEdges.Add(newController, newElement);
- }
- }
- }
- }
- public Vector2 ScreenToViewPosition(Vector2 position)
- {
- GUIView guiView = panel.InternalGetGUIView();
- if (guiView == null)
- return position;
- return position - guiView.screenPosition.position;
- }
- public Vector2 ViewToScreenPosition(Vector2 position)
- {
- GUIView guiView = panel.InternalGetGUIView();
- if (guiView == null)
- return position;
- return position + guiView.screenPosition.position;
- }
- void OnCreateNode(NodeCreationContext ctx)
- {
- GUIView guiView = panel.InternalGetGUIView();
- if (guiView == null)
- return;
- Vector2 point = ScreenToViewPosition(ctx.screenMousePosition);
- List<VisualElement> picked = new List<VisualElement>();
- panel.PickAll(point, picked);
- VFXContextUI context = picked.OfType<VFXContextUI>().FirstOrDefault();
- if (context != null)
- {
- if (context.canHaveBlocks)
- context.OnCreateBlock(point);
- }
- else
- {
- VFXDataEdge edge = picked.OfType<VFXDataEdge>().FirstOrDefault();
- if (edge != null)
- VFXFilterWindow.Show(VFXViewWindow.currentWindow, point, ctx.screenMousePosition, new VFXNodeProvider(controller, (d, v) => AddNodeOnEdge(d, v, edge.controller), null, new Type[] { typeof(VFXOperator) }));
- else
- VFXFilterWindow.Show(VFXViewWindow.currentWindow, point, ctx.screenMousePosition, m_NodeProvider);
- }
- }
- public void CreateTemplateSystem(string path, Vector2 tPos, VFXGroupNode groupNode)
- {
- var resource = VisualEffectResource.GetResourceAtPath(path);
- if (resource != null)
- {
- VFXViewController templateController = VFXViewController.GetController(resource, true);
- templateController.useCount++;
- var data = VFXCopy.SerializeElements(templateController.allChildren, templateController.graph.UIInfos.uiBounds);
- VFXPaste.UnserializeAndPasteElements(controller, tPos, data, this, groupNode != null ? groupNode.controller : null);
- templateController.useCount--;
- }
- }
- void OnToggleCompile(ChangeEvent<bool> e)
- {
- VFXViewWindow.currentWindow.autoCompile = !VFXViewWindow.currentWindow.autoCompile;
- }
- void OnResyncMaterial()
- {
- controller.graph.Invalidate(VFXModel.InvalidationCause.kMaterialChanged);
- }
- void OnCompile()
- {
- VFXLibrary.LogUnsupportedSRP();
- if (controller.model.isSubgraph)
- controller.graph.RecompileIfNeeded(false, false);
- else
- {
- VFXGraph.explicitCompile = true;
- using (var reporter = new VFXCompileErrorReporter(controller.graph.errorManager))
- {
- VFXGraph.compileReporter = reporter;
- AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(controller.model));
- VFXGraph.compileReporter = null;
- }
- VFXGraph.explicitCompile = false;
- }
- }
- void OnSave()
- {
- m_ComponentBoard?.DeactivateBoundsRecordingIfNeeded(); //Avoids saving the graph with unnecessary bounds computations
- var graphToSave = new HashSet<VFXGraph>();
- GetGraphsRecursively(controller.graph, graphToSave);
- foreach (var graph in graphToSave)
- {
- if (EditorUtility.IsDirty(graph) || UnityEngine.Object.ReferenceEquals(graph, controller.graph))
- {
- graph.UpdateSubAssets();
- try
- {
- VFXGraph.compilingInEditMode = !m_IsRuntimeMode;
- graph.GetResource().WriteAsset();
- }
- finally
- {
- VFXGraph.compilingInEditMode = false;
- }
- }
- }
- }
- void GetGraphsRecursively(VFXGraph start, HashSet<VFXGraph> graphs)
- {
- if (graphs.Contains(start))
- return;
- graphs.Add(start);
- foreach (var child in start.children)
- {
- if (child is VFXSubgraphOperator ope)
- {
- if (ope.subgraph != null)
- {
- var graph = ope.subgraph.GetResource().GetOrCreateGraph();
- GetGraphsRecursively(graph, graphs);
- }
- }
- else if (child is VFXSubgraphContext subCtx)
- {
- if (subCtx.subgraph != null)
- {
- var graph = subCtx.subgraph.GetResource().GetOrCreateGraph();
- GetGraphsRecursively(graph, graphs);
- }
- }
- else if (child is VFXContext ctx)
- {
- foreach (var block in ctx.children.Cast<VFXBlock>())
- {
- if (block is VFXSubgraphBlock subBlock)
- {
- if (subBlock.subgraph != null)
- {
- var graph = subBlock.subgraph.GetResource().GetOrCreateGraph();
- GetGraphsRecursively(graph, graphs);
- }
- }
- }
- }
- }
- }
- public EventPropagation Compile()
- {
- OnCompile();
- return EventPropagation.Stop;
- }
- void AddVFXParameter(Vector2 pos, VFXParameterController parameterController, VFXGroupNode groupNode)
- {
- if (controller == null || parameterController == null) return;
- controller.AddVFXParameter(pos, parameterController, groupNode != null ? groupNode.controller : null);
- }
- public EventPropagation Resync()
- {
- foreach (var node in rootNodes.Values)
- node.RemoveFromHierarchy();
- rootNodes.Clear();
- foreach (var node in nodes.ToList())
- node.RemoveFromHierarchy();
- foreach (var edge in dataEdges.Values)
- edge.RemoveFromHierarchy();
- dataEdges.Clear();
- foreach (var edge in flowEdges.Values)
- edge.RemoveFromHierarchy();
- flowEdges.Clear();
- foreach (var edge in edges.ToList())
- edge.RemoveFromHierarchy();
- if (controller != null)
- controller.ForceReload();
- return EventPropagation.Stop;
- }
- public EventPropagation OutputToDot()
- {
- if (controller == null) return EventPropagation.Stop;
- DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.None, "expGraph_None.dot");
- return EventPropagation.Stop;
- }
- public EventPropagation OutputToDotReduced()
- {
- if (controller == null) return EventPropagation.Stop;
- DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.Reduction, "expGraph_Reduction.dot");
- return EventPropagation.Stop;
- }
- public EventPropagation OutputToDotConstantFolding()
- {
- if (controller == null) return EventPropagation.Stop;
- DotGraphOutput.DebugExpressionGraph(controller.graph, VFXExpressionContextOption.ConstantFolding, "expGraph_ConstantFolding.dot");
- return EventPropagation.Stop;
- }
- IEnumerable<VisualEffect> GetActiveComponents()
- {
- if (attachedComponent != null)
- yield return attachedComponent;
- else
- {
- foreach (var component in UnityEngine.VFX.VFXManager.GetComponents())
- yield return component;
- }
- }
- public EventPropagation ReinitComponents()
- {
- foreach (var component in GetActiveComponents())
- component.Reinit();
- return EventPropagation.Stop;
- }
- public EventPropagation ReinitAndPlayComponents()
- {
- foreach (var component in GetActiveComponents())
- {
- component.Reinit();
- component.Play();
- }
- return EventPropagation.Stop;
- }
- public IEnumerable<VFXContextUI> GetAllContexts()
- {
- foreach (var layer in contentViewContainer.Children())
- {
- foreach (var element in layer.Children())
- {
- if (element is VFXContextUI)
- {
- yield return element as VFXContextUI;
- }
- }
- }
- }
- public IEnumerable<VFXNodeUI> GetAllNodes()
- {
- foreach (var layer in contentViewContainer.Children())
- {
- foreach (var element in layer.Children())
- {
- if (element is VFXNodeUI)
- {
- yield return element as VFXNodeUI;
- }
- }
- }
- }
- public override List<Port> GetCompatiblePorts(Port startAnchor, NodeAdapter nodeAdapter)
- {
- if (controller == null) return null;
- if (startAnchor is VFXDataAnchor)
- {
- var controllers = controller.GetCompatiblePorts((startAnchor as VFXDataAnchor).controller, nodeAdapter);
- return controllers.Select(t => (Port)GetDataAnchorByController(t as VFXDataAnchorController)).ToList();
- }
- else
- {
- var controllers = controller.GetCompatiblePorts((startAnchor as VFXFlowAnchor).controller, nodeAdapter);
- return controllers.Select(t => (Port)GetFlowAnchorByController(t as VFXFlowAnchorController)).ToList();
- }
- }
- public IEnumerable<VFXFlowAnchor> GetAllFlowAnchors(bool input, bool output)
- {
- foreach (var context in GetAllContexts())
- {
- foreach (VFXFlowAnchor anchor in context.GetFlowAnchors(input, output))
- {
- yield return anchor;
- }
- }
- }
- void VFXElementResized(VisualElement element)
- {
- if (element is IVFXResizable)
- {
- (element as IVFXResizable).OnResized();
- }
- }
- GraphViewChange VFXGraphViewChanged(GraphViewChange change)
- {
- if (change.movedElements != null && change.movedElements.Count > 0)
- {
- HashSet<IVFXMovable> movables = new HashSet<IVFXMovable>(change.movedElements.OfType<IVFXMovable>());
- foreach (var groupNode in groupNodes.Values)
- {
- var containedElements = groupNode.containedElements;
- if (containedElements != null && containedElements.Intersect(change.movedElements).Count() > 0)
- {
- groupNode.UpdateGeometryFromContent();
- movables.Add(groupNode);
- }
- }
- foreach (var groupNode in change.movedElements.OfType<VFXGroupNode>())
- {
- var containedElements = groupNode.containedElements;
- if (containedElements != null)
- {
- foreach (var node in containedElements.OfType<IVFXMovable>())
- {
- movables.Add(node);
- }
- }
- }
- foreach (var movable in movables)
- {
- movable.OnMoved();
- }
- }
- else if (change.elementsToRemove != null)
- {
- controller.Remove(change.elementsToRemove.OfType<IControlledElement>().Where(t => t.controller != null).Select(t => t.controller));
- foreach (var dataEdge in change.elementsToRemove.OfType<VFXDataEdge>())
- {
- RemoveElement(dataEdge);
- dataEdges.Remove(dataEdge.controller);
- }
- }
- return change;
- }
- public VFXNodeUI GetNodeByController(VFXNodeController controller)
- {
- if (controller is VFXBlockController)
- {
- var blockController = (controller as VFXBlockController);
- VFXContextUI context = GetNodeByController(blockController.contextController) as VFXContextUI;
- return context.GetAllBlocks().FirstOrDefault(t => t.controller == blockController);
- }
- return GetAllNodes().FirstOrDefault(t => t.controller == controller);
- }
- public VFXDataAnchor GetDataAnchorByController(VFXDataAnchorController controller)
- {
- if (controller == null)
- return null;
- VFXNodeUI node = GetNodeByController(controller.sourceNode);
- if (node == null)
- {
- Debug.LogError("Can't find the node for a given node controller");
- return null;
- }
- VFXDataAnchor anchor = node.GetPorts(controller.direction == Direction.Input, controller.direction == Direction.Output).FirstOrDefault(t => t.controller == controller);
- if (anchor == null)
- {
- // Can happen because the order of the DataWatch is not controlled
- node.ForceUpdate();
- anchor = node.GetPorts(controller.direction == Direction.Input, controller.direction == Direction.Output).FirstOrDefault(t => t.controller == controller);
- }
- return anchor;
- }
- public VFXFlowAnchor GetFlowAnchorByController(VFXFlowAnchorController controller)
- {
- if (controller == null)
- return null;
- return GetAllFlowAnchors(controller.direction == Direction.Input, controller.direction == Direction.Output).Where(t => t.controller == controller).FirstOrDefault();
- }
- public IEnumerable<VFXDataAnchor> GetAllDataAnchors(bool input, bool output)
- {
- foreach (var layer in contentViewContainer.Children())
- {
- foreach (var element in layer.Children())
- {
- if (element is VFXNodeUI)
- {
- var ope = element as VFXNodeUI;
- foreach (VFXDataAnchor anchor in ope.GetPorts(input, output))
- yield return anchor;
- if (element is VFXContextUI)
- {
- var context = element as VFXContextUI;
- foreach (VFXBlockUI block in context.GetAllBlocks())
- {
- foreach (VFXDataAnchor anchor in block.GetPorts(input, output))
- yield return anchor;
- }
- }
- }
- }
- }
- }
- public VFXDataEdge GetDataEdgeByController(VFXDataEdgeController controller)
- {
- foreach (var layer in contentViewContainer.Children())
- {
- foreach (var element in layer.Children())
- {
- if (element is VFXDataEdge)
- {
- VFXDataEdge candidate = element as VFXDataEdge;
- if (candidate.controller == controller)
- return candidate;
- }
- }
- }
- return null;
- }
- public void UpdateGlobalSelection()
- {
- if (controller == null) return;
- 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();
- if (objectSelected.Length > 0)
- {
- Selection.objects = objectSelected;
- Selection.objects = objectSelected;
- return;
- }
- var blackBoardSelected = selection.OfType<BlackboardField>().Select(t => t.GetFirstAncestorOfType<VFXBlackboardRow>().controller.model).ToArray();
- if (blackBoardSelected.Length > 0)
- {
- Selection.objects = blackBoardSelected;
- return;
- }
- }
- void SelectAsset()
- {
- if (Selection.activeObject != controller.model)
- {
- Selection.activeObject = controller.model.visualEffectObject;
- EditorGUIUtility.PingObject(controller.model.visualEffectObject);
- }
- }
- void Checkout()
- {
- Task task = Provider.Checkout(controller.model.visualEffectObject, CheckoutMode.Both);
- task.Wait();
- OnFocus();
- }
- void ElementAddedToGroupNode(Group groupNode, IEnumerable<GraphElement> elements)
- {
- (groupNode as VFXGroupNode).ElementsAddedToGroupNode(elements);
- }
- void ElementRemovedFromGroupNode(Group groupNode, IEnumerable<GraphElement> elements)
- {
- (groupNode as VFXGroupNode).ElementsRemovedFromGroupNode(elements);
- }
- void GroupNodeTitleChanged(Group groupNode, string title)
- {
- (groupNode as VFXGroupNode).GroupNodeTitleChanged(title);
- }
- private void AddRangeToSelection(List<ISelectable> selectables)
- {
- selectables.ForEach(base.AddToSelection);
- UpdateGlobalSelection();
- }
- public override void AddToSelection(ISelectable selectable)
- {
- base.AddToSelection(selectable);
- UpdateGlobalSelection();
- }
- public override void RemoveFromSelection(ISelectable selectable)
- {
- base.RemoveFromSelection(selectable);
- UpdateGlobalSelection();
- }
- public override void ClearSelection()
- {
- bool selectionEmpty = selection.Count() == 0;
- base.ClearSelection();
- if (!selectionEmpty)
- UpdateGlobalSelection();
- }
- VFXBlackboard m_Blackboard;
- VFXComponentBoard m_ComponentBoard;
- public VFXBlackboard blackboard
- {
- get { return m_Blackboard; }
- }
- protected internal override bool canCopySelection
- {
- get { return selection.OfType<VFXNodeUI>().Any() || selection.OfType<Group>().Any() || selection.OfType<VFXContextUI>().Any(t => !(t.controller.model is VFXBlockSubgraphContext)) || selection.OfType<VFXStickyNote>().Any(); }
- }
- IEnumerable<Controller> ElementsToController(IEnumerable<GraphElement> elements)
- {
- return elements.OfType<IControlledElement>().Select(t => t.controller);
- }
- void CollectElements(IEnumerable<GraphElement> elements, HashSet<GraphElement> elementsToCopySet)
- {
- foreach (var element in elements)
- {
- if (element is Group)
- {
- CollectElements((element as Group).containedElements, elementsToCopySet);
- elementsToCopySet.Add(element);
- }
- else if (element is Node || element is VFXContextUI || element is VFXStickyNote)
- {
- elementsToCopySet.Add(element);
- }
- }
- }
- protected internal override void CollectCopyableGraphElements(IEnumerable<GraphElement> elements, HashSet<GraphElement> elementsToCopySet)
- {
- CollectElements(elements, elementsToCopySet);
- var nodeuis = new HashSet<VFXNodeUI>(elementsToCopySet.SelectMany(t => t.Query().OfType<VFXNodeUI>().ToList()));
- var contextuis = new HashSet<VFXContextUI>(elementsToCopySet.OfType<VFXContextUI>());
- foreach (var edge in edges.ToList())
- {
- if (edge is VFXDataEdge)
- {
- if (nodeuis.Contains(edge.input.GetFirstAncestorOfType<VFXNodeUI>()) && nodeuis.Contains(edge.output.GetFirstAncestorOfType<VFXNodeUI>()))
- {
- elementsToCopySet.Add(edge);
- }
- }
- else
- {
- if (contextuis.Contains(edge.input.GetFirstAncestorOfType<VFXContextUI>()) && contextuis.Contains(edge.output.GetFirstAncestorOfType<VFXContextUI>()))
- {
- elementsToCopySet.Add(edge);
- }
- }
- }
- }
- Rect GetElementsBounds(IEnumerable<GraphElement> elements)
- {
- Rect[] elementBounds = elements.Where(t => !(t is VFXEdge)).Select(t => contentViewContainer.WorldToLocal(t.worldBound)).ToArray();
- if (elementBounds.Length < 1) return Rect.zero;
- Rect bounds = elementBounds[0];
- for (int i = 1; i < elementBounds.Length; ++i)
- {
- 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));
- }
- // Round to avoid changes in the asset because of the zoom level.
- bounds.x = Mathf.Round(bounds.x);
- bounds.y = Mathf.Round(bounds.y);
- bounds.width = Mathf.Round(bounds.width);
- bounds.height = Mathf.Round(bounds.height);
- return bounds;
- }
- public string SerializeElements(IEnumerable<GraphElement> elements)
- {
- Profiler.BeginSample("VFXCopy.SerializeElements");
- string result = VFXCopy.SerializeElements(ElementsToController(elements), GetElementsBounds(elements));
- Profiler.EndSample();
- return result;
- }
- public EventPropagation DuplicateSelectionWithEdges()
- {
- List<Controller> sourceControllers = selection.OfType<IControlledElement>().Select(t => t.controller).ToList();
- Rect bounds = GetElementsBounds(selection.OfType<IControlledElement>().OfType<GraphElement>());
- object result = VFXCopy.Copy(sourceControllers, bounds);
- var targetControllers = new List<VFXNodeController>();
- VFXPaste.Paste(controller, pasteCenter, result, this, null, targetControllers);
- ClearSelection();
- for (int i = 0; i < sourceControllers.Count; ++i)
- {
- if (targetControllers[i] != null)
- {
- CopyInputLinks(sourceControllers[i] as VFXNodeController, targetControllers[i]);
- if (targetControllers[i] is VFXBlockController blkController)
- AddToSelection((rootNodes[blkController.contextController] as VFXContextUI).GetAllBlocks().First(t => t.controller == blkController));
- else
- AddToSelection(rootNodes[targetControllers[i]]);
- }
- }
- return EventPropagation.Stop;
- }
- public void AddToSelection(VFXModel model, int id)
- {
- VFXNodeController nodeController = controller.GetRootNodeController(model, id);
- if (nodeController != null)
- {
- AddToSelection(rootNodes[nodeController]);
- }
- }
- public void AddParameterToSelection(VFXParameter parameter)
- {
- VFXParameterController parameterController = controller.GetParameterController(parameter);
- if (parameterController != null)
- {
- m_Blackboard.AddToSelection(m_Blackboard.GetRowFromController(parameterController).field);
- }
- }
- void CopyInputLinks(VFXNodeController sourceController, VFXNodeController targetController)
- {
- foreach (var st in sourceController.inputPorts.Zip(targetController.inputPorts, (s, t) => new { source = s, target = t }))
- {
- CopyInputLinks(st.source, st.target);
- }
- if (sourceController is VFXContextController sourceContext && targetController is VFXContextController targetContext)
- {
- foreach (var st in sourceContext.blockControllers.Zip(targetContext.blockControllers, (s, t) => new { source = s, target = t }))
- {
- CopyInputLinks(st.source, st.target);
- }
- }
- }
- void CopyInputLinks(VFXDataAnchorController sourceSlot, VFXDataAnchorController targetSlot)
- {
- if (sourceSlot.portType != targetSlot.portType)
- return;
- if (sourceSlot.HasLink())
- controller.CreateLink(targetSlot, controller.dataEdges.First(t => t.input == sourceSlot).output);
- }
- Vector2 pasteCenter
- {
- get
- {
- Vector2 center = layout.size * 0.5f;
- center = this.ChangeCoordinatesTo(contentViewContainer, center);
- return center;
- }
- }
- private bool VFXCanPaste(string data)
- {
- return VFXPaste.CanPaste(this, data);
- }
- public void UnserializeAndPasteElements(string operationName, string data)
- {
- Profiler.BeginSample("VFXPaste.VFXPaste.UnserializeAndPasteElements");
- VFXPaste.UnserializeAndPasteElements(controller, pasteCenter, data, this);
- Profiler.EndSample();
- }
- private bool TryGetOverlappingContextAbove(VFXContextUI context, out VFXContextUI overlappingContext, out float distance)
- {
- var rect = context.GetPosition();
- var posY = context.controller.model.position.y;
- var overlappingContexts = new Dictionary<VFXContextUI, float>();
- foreach (var ctx in GetAllContexts())
- {
- if (ctx == context)
- {
- continue;
- }
- var ctxRect = ctx.GetPosition();
- var ctxPosY = ctx.controller.model.position.y;
- // Skip contexts that are side by side
- if (rect.xMin - ctxRect.xMax > -5 || rect.xMax - ctxRect.xMin < 5)
- {
- continue;
- }
- distance = posY - ctxPosY - ctxRect.height;
- if (distance < 0 && posY > ctxRect.yMin)
- {
- overlappingContexts[ctx] = -distance;
- }
- }
- if (overlappingContexts.Any())
- {
- var keyPair = overlappingContexts.OrderByDescending(x => x.Value).First();
- overlappingContext = keyPair.Key;
- distance = keyPair.Value;
- return true;
- }
- distance = 0f;
- overlappingContext = null;
- return false;
- }
- public void PushUnderContext(VFXContextUI context, float size)
- {
- if (size < 5) return;
- foreach (var edge in edges.OfType<VFXFlowEdge>().SkipWhile(x => x.output.GetFirstAncestorOfType<VFXContextUI>() != context))
- {
- context = edge.input.GetFirstAncestorOfType<VFXContextUI>();
- if (TryGetOverlappingContextAbove(context, out var aboveContext, out var distance))
- {
- var rect = context.GetPosition();
- context.controller.position = new Vector2(rect.x, rect.y + distance);
- }
- }
- }
- bool canGroupSelection
- {
- get
- {
- return canCopySelection && !selection.Any(t => t is Group);
- }
- }
- void OnEnterPanel(AttachToPanelEvent e)
- {
- Undo.undoRedoPerformed += OnUndoPerformed;
- }
- void OnLeavePanel(DetachFromPanelEvent e)
- {
- Undo.undoRedoPerformed -= OnUndoPerformed;
- }
- private void OnKeyDownEvent(KeyDownEvent evt)
- {
- if (evt.keyCode == KeyCode.D && evt.modifiers == EventModifiers.Control)
- {
- DuplicateBlackboardFieldSelection();
- DuplicateBlackBoardCategorySelection();
- }
- }
- public void ValidateCommand(ValidateCommandEvent evt)
- {
- if (evt.commandName == "SelectAll")
- {
- evt.StopPropagation();
- if (evt.imguiEvent != null)
- {
- evt.imguiEvent.Use();
- }
- }
- }
- public void ExecuteCommand(ExecuteCommandEvent e)
- {
- if (e.commandName == "SelectAll")
- {
- ClearSelection();
- AddRangeToSelection(graphElements.Where(x => x is not VFXSystemBorder).OfType<ISelectable>().ToList());
- e.StopPropagation();
- }
- }
- void GroupSelection()
- {
- controller.GroupNodes(selection.OfType<ISettableControlledElement<VFXNodeController>>().Select(t => t.controller));
- }
- void AddStickyNote(Vector2 position, VFXGroupNode group = null)
- {
- position = contentViewContainer.WorldToLocal(position);
- controller.AddStickyNote(position, group != null ? group.controller : null);
- }
- void OnCreateNodeInGroupNode(DropdownMenuAction e)
- {
- //The targeted groupnode will be determined by a PickAll later
- VFXFilterWindow.Show(VFXViewWindow.currentWindow, e.eventInfo.mousePosition, ViewToScreenPosition(e.eventInfo.mousePosition), m_NodeProvider);
- }
- void OnEnterSubgraph(DropdownMenuAction e)
- {
- var node = e.userData as VFXModel;
- if (node is VFXSubgraphOperator subGraph)
- {
- VFXViewWindow.currentWindow.PushResource(subGraph.subgraph.GetResource());
- }
- else if (node is VFXSubgraphBlock subGraph2)
- {
- VFXViewWindow.currentWindow.PushResource(subGraph2.subgraph.GetResource());
- }
- else if (node is VFXSubgraphContext subGraph3)
- {
- VFXViewWindow.currentWindow.PushResource(subGraph3.subgraph.GetResource());
- }
- }
- void OnCreateNodeOnEdge(DropdownMenuAction e)
- {
- 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) }));
- }
- void AddNodeOnEdge(VFXNodeProvider.Descriptor desc, Vector2 position, VFXDataEdgeController edge)
- {
- position = this.ChangeCoordinatesTo(contentViewContainer, position);
- position.x -= 60;
- position.y -= 60;
- position = contentViewContainer.ChangeCoordinatesTo(this, position);
- var newNodeController = AddNode(desc, position);
- if (newNodeController == null)
- return;
- foreach (var outputPort in newNodeController.outputPorts)
- {
- if (controller.CreateLink(edge.input, outputPort))
- break;
- }
- foreach (var inputPort in newNodeController.inputPorts)
- {
- if (controller.CreateLink(inputPort, edge.output))
- break;
- }
- }
- public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
- {
- if (controller == null || !IsAssetEditable())
- return;
- if (evt.target is VFXGroupNode || evt.target is VFXSystemBorder) // Default behaviour only shows the OnCreateNode if the target is the view itself.
- evt.target = this;
- base.BuildContextualMenu(evt);
- Vector2 mousePosition = evt.mousePosition;
- if (evt.target is VFXNodeUI node)
- {
- evt.menu.InsertAction(evt.target is VFXContextUI ? 1 : 0, "Group Selection", (e) => { GroupSelection(); },
- (e) => { return canGroupSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
- 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))
- {
- evt.menu.AppendAction("Enter Subgraph", OnEnterSubgraph, e => DropdownMenuAction.Status.Normal, node.controller.model);
- }
- evt.menu.AppendAction("Clear Ignored Errors", a => node.controller.model.ClearIgnoredErrors(), node.controller.model.HasIgnoredErrors() ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
- }
- if (evt.target is VFXDataEdge edge)
- {
- evt.menu.InsertAction(0, "Create Node", OnCreateNodeOnEdge, t => DropdownMenuAction.Status.Normal, edge.controller);
- }
- if (evt.target is VFXView)
- {
- evt.menu.InsertAction(1, "Create Sticky Note", (e) => { AddStickyNote(mousePosition); }, (e) => DropdownMenuAction.Status.Normal);
- if (evt.triggerEvent is IMouseEvent)
- {
- foreach (var system in m_Systems)
- {
- Rect bounds = system.worldBound;
- if (bounds.Contains((evt.triggerEvent as IMouseEvent).mousePosition))
- {
- evt.menu.InsertSeparator("", 2);
- evt.menu.InsertAction(3, string.IsNullOrEmpty(system.controller.title) ? "Name System" : "Rename System", a => system.OnRename(), e => DropdownMenuAction.Status.Normal);
- break;
- }
- }
- }
- if (VFXViewWindow.currentWindow != null && VFXViewWindow.currentWindow.resourceHistory.Count() > 0)
- {
- evt.menu.AppendAction(" Back To Parent Graph", e => VFXViewWindow.currentWindow.PopResource());
- }
- }
- if (evt.target is VFXContextUI)
- {
- var context = evt.target as VFXContextUI;
- evt.menu.InsertSeparator("", 2);
- evt.menu.InsertAction(3, string.IsNullOrEmpty(context.controller.model.label) ? "Name Context" : "Rename Context", a => context.OnRename(), e => DropdownMenuAction.Status.Normal);
- }
- if (selection.OfType<VFXNodeUI>().Any() && evt.target is VFXNodeUI)
- {
- if (selection.OfType<VFXOperatorUI>().Any() && !selection.OfType<VFXNodeUI>().Any(t => !(t is VFXOperatorUI) && !(t is VFXParameterUI)))
- evt.menu.InsertAction(3, "Convert To Subgraph Operator", ToSubgraphOperator, e => DropdownMenuAction.Status.Normal);
- else if (SelectionHasCompleteSystems())
- evt.menu.InsertAction(3, "Convert To Subgraph", ToSubgraphContext, e => DropdownMenuAction.Status.Normal);
- else if (selection.OfType<VFXBlockUI>().Any() && selection.OfType<VFXBlockUI>().Select(t => t.context).Distinct().Count() == 1)
- {
- evt.menu.InsertAction(3, "Convert to Subgraph Block", ToSubgraphBlock, e => DropdownMenuAction.Status.Normal);
- }
- }
- if (evt.target is GraphView || evt.target is Node || evt.target is Group)
- {
- evt.menu.AppendAction("Duplicate with edges", (a) => { DuplicateSelectionWithEdges(); },
- (a) => { return canDuplicateSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
- evt.menu.AppendSeparator();
- }
- if (selection.OfType<VFXOperatorUI>().Any(t => !t.superCollapsed))
- evt.menu.AppendAction("Collapse Operators", CollapseOperator, e => DropdownMenuAction.Status.Normal, true);
- if (selection.OfType<VFXOperatorUI>().Any(t => t.superCollapsed))
- evt.menu.AppendAction("Uncollapse Operators", CollapseOperator, e => DropdownMenuAction.Status.Normal, false);
- if (selection.OfType<VFXStickyNote>().Any() && evt.menu.MenuItems().OfType<DropdownMenuAction>().All(x => x.name != "Delete"))
- {
- evt.menu.AppendSeparator();
- evt.menu.AppendAction("Delete", OnDeleteStickyNote, e => canDeleteSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
- }
- if (selection.OfType<VFXBlackboardCategory>().Any())
- {
- evt.menu.AppendSeparator();
- evt.menu.AppendAction("Duplicate %d", OnDuplicateBlackBoardCategory, e => canDeleteSelection ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
- }
- if (evt.target is GraphView || evt.target is Node)
- {
- var copyMenu = evt.menu.MenuItems().OfType<DropdownMenuAction>().SingleOrDefault(x => x.name == "Copy");
- if (copyMenu != null)
- {
- var index = evt.menu.MenuItems().IndexOf(copyMenu);
- evt.menu.InsertAction(index + 1, "Paste", (a) => { PasteCallback(); }, (a) => { return canPaste ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; });
- }
- }
- }
- static readonly string s_DeleteEventCommandName = GetDeleteEventCommandName();
- static string GetDeleteEventCommandName()
- {
- var fieldInfo = Type.GetType("UnityEngine.EventCommandNames, UnityEngine")?.GetField("Delete", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
- if (fieldInfo != null)
- {
- if (fieldInfo.GetValue(null) is string commandName)
- {
- return commandName;
- }
- Debug.Log("API has changed, Delete command name field is either null or not a string anymore");
- }
- else
- {
- Debug.Log("API has changed, could not retrieve Delete command name field using reflection");
- }
- return "Delete";
- }
- void OnDeleteStickyNote(DropdownMenuAction menuAction)
- {
- using var ev = ExecuteCommandEvent.GetPooled(s_DeleteEventCommandName);
- SendEvent(ev);
- }
- private void OnDuplicateBlackBoardCategory(DropdownMenuAction obj)
- {
- DuplicateBlackBoardCategorySelection();
- }
- void CollapseOperator(DropdownMenuAction a)
- {
- bool collapse = (bool)a.userData;
- foreach (var ope in selection.OfType<VFXOperatorUI>())
- ope.controller.superCollapsed = collapse;
- }
- public bool SelectionHasCompleteSystems()
- {
- HashSet<VFXContextUI> selectedContextUIs = new HashSet<VFXContextUI>(selection.OfType<VFXContextUI>());
- if (selectedContextUIs.Count() < 1)
- return false;
- var relatedContext = selectedContextUIs.Select(t => t.controller.model);
- //Adding manually VFXBasicGPUEvent, it doesn't appears as dependency.
- var outputContextDataFromGPUEvent = relatedContext.OfType<VFXBasicGPUEvent>().SelectMany(o => o.outputContexts);
- relatedContext = relatedContext.Concat(outputContextDataFromGPUEvent);
- var selectedContextDatas = relatedContext.Select(o => o.GetData()).Where(o => o != null);
- var selectedContextDependencies = selectedContextDatas.SelectMany(o => o.allDependenciesIncludingNotCompilable);
- var allDatas = selectedContextDatas.Concat(selectedContextDependencies);
- var allDatasHash = new HashSet<VFXData>(allDatas);
- foreach (var context in GetAllContexts())
- {
- var model = context.controller.model;
- if (model is VFXBlockSubgraphContext)
- return false;
- //We should exclude model.contextType == VFXContextType.Event of this condition.
- //If VFXConvertSubgraph.TransferContextsFlowEdges has been fixed & renabled.
- if (allDatasHash.Contains(model.GetData()) && !selectedContextUIs.Contains(context))
- return false;
- }
- return true;
- }
- void ToSubgraphBlock(DropdownMenuAction a)
- {
- VFXConvertSubgraph.ConvertToSubgraphBlock(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
- }
- void ToSubgraphOperator(DropdownMenuAction a)
- {
- VFXConvertSubgraph.ConvertToSubgraphOperator(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
- }
- void ToSubgraphContext(DropdownMenuAction a)
- {
- VFXConvertSubgraph.ConvertToSubgraphContext(this, selection.OfType<IControlledElement>().Select(t => t.controller), GetElementsBounds(selection.Where(t => !(t is Edge)).Cast<GraphElement>()));
- }
- List<VFXSystemBorder> m_Systems = new List<VFXSystemBorder>();
- public ReadOnlyCollection<VFXSystemBorder> systems
- {
- get { return m_Systems.AsReadOnly(); }
- }
- public void UpdateSystemNames()
- {
- if (m_Systems != null)
- foreach (var system in m_Systems)
- {
- system.Update();
- }
- }
- public void UpdateSystems()
- {
- while (m_Systems.Count() > controller.systems.Count())
- {
- VFXSystemBorder border = m_Systems.Last();
- m_Systems.RemoveAt(m_Systems.Count - 1);
- border.RemoveFromHierarchy();
- }
- UpdateSystemNames();
- while (m_Systems.Count() < controller.systems.Count())
- {
- VFXSystemBorder border = new VFXSystemBorder();
- m_Systems.Add(border);
- AddElement(border);
- border.controller = controller.systems[m_Systems.Count() - 1];
- }
- foreach (var context in GetAllContexts())
- {
- context.UpdateLabel();
- }
- }
- void OnDragUpdated(DragUpdatedEvent e)
- {
- if (controller == null || !IsAssetEditable())
- return;
- if (DragAndDrop.GetGenericData("DragSelection") != null && selection.Any(t => t is VFXBlackboardField && (t as VFXBlackboardField).GetFirstAncestorOfType<VFXBlackboardRow>() != null))
- {
- VFXBlackboardField selectedField = selection.OfType<VFXBlackboardField>().Where(t => t.GetFirstAncestorOfType<VFXBlackboardRow>() != null).First();
- if (selectedField.controller.isOutput && selectedField.controller.nodeCount > 0)
- {
- return;
- }
- DragAndDrop.visualMode = DragAndDropVisualMode.Link;
- e.StopPropagation();
- }
- else
- {
- var references = DragAndDrop.objectReferences.OfType<VisualEffectAsset>().Cast<VisualEffectObject>().Concat(DragAndDrop.objectReferences.OfType<VisualEffectSubgraphOperator>());
- VisualEffectObject draggedObject = references.FirstOrDefault();
- bool isOperator = draggedObject is VisualEffectSubgraphOperator;
- if (draggedObject != null && draggedObject != controller.model.visualEffectObject)
- {
- var draggedObjectDependencies = draggedObject.GetResource().GetOrCreateGraph().subgraphDependencies;
- bool vfxIntovfx = !isOperator && !controller.model.isSubgraph && !draggedObjectDependencies.Contains(controller.model.subgraph); // dropping a vfx into a vfx
- bool operatorIntovfx = isOperator && !controller.model.isSubgraph; //dropping an operator into a vfx
- bool operatorIntoOperator = isOperator && controller.model.visualEffectObject is VisualEffectSubgraphOperator && !draggedObjectDependencies.Contains(controller.model.visualEffectObject); //dropping an operator into a vfx
- if (vfxIntovfx || operatorIntovfx || operatorIntoOperator)
- {
- DragAndDrop.visualMode = DragAndDropVisualMode.Link;
- e.StopPropagation();
- }
- return;
- }
- var droppedBlocks = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>();
- if (droppedBlocks.Count() > 0 && !controller.model.isSubgraph)
- {
- DragAndDrop.visualMode = DragAndDropVisualMode.Link;
- e.StopPropagation();
- }
- }
- }
- void OnDragPerform(DragPerformEvent e)
- {
- if (controller == null || !IsAssetEditable())
- return;
- var groupNode = GetPickedGroupNode(e.mousePosition);
- if (DragAndDrop.GetGenericData("DragSelection") != null && selection.Any(t => t is BlackboardField && (t as BlackboardField).GetFirstAncestorOfType<VFXBlackboardRow>() != null))
- {
- var rows = selection.OfType<BlackboardField>().Select(t => t.GetFirstAncestorOfType<VFXBlackboardRow>()).Where(t => t != null).ToArray();
- if (rows.Length > 0)
- {
- DragAndDrop.AcceptDrag();
- Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
- UpdateSelectionWithNewNode();
- float cpt = 0;
- foreach (var row in rows)
- {
- AddVFXParameter(mousePosition - new Vector2(50, 20) + cpt * new Vector2(0, 40), row.controller, groupNode);
- ++cpt;
- }
- e.StopPropagation();
- }
- }
- else
- {
- DragAndDrop.AcceptDrag();
- var references = DragAndDrop.objectReferences.OfType<VisualEffectAsset>().Cast<VisualEffectObject>().Concat(DragAndDrop.objectReferences.OfType<VisualEffectSubgraphOperator>());
- VisualEffectObject draggedObject = references.FirstOrDefault();
- bool isOperator = draggedObject is VisualEffectSubgraphOperator;
- if (draggedObject != null && draggedObject != controller.model.visualEffectObject)
- {
- var draggedObjectDependencies = draggedObject.GetResource().GetOrCreateGraph().subgraphDependencies;
- bool vfxIntovfx = !isOperator && !controller.model.isSubgraph && !draggedObjectDependencies.Contains(controller.model.subgraph); // dropping a vfx into a vfx
- bool operatorIntovfx = isOperator && !controller.model.isSubgraph; //dropping an operator into a vfx
- bool operatorIntoOperator = isOperator && controller.model.visualEffectObject is VisualEffectSubgraphOperator && !draggedObjectDependencies.Contains(controller.model.visualEffectObject); //dropping an operator into a vfx
- if (vfxIntovfx || operatorIntovfx || operatorIntoOperator)
- {
- Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
- VFXModel newModel = (references.First() is VisualEffectAsset) ? VFXSubgraphContext.CreateInstance<VFXSubgraphContext>() as VFXModel : VFXSubgraphOperator.CreateInstance<VFXSubgraphOperator>() as VFXModel;
- UpdateSelectionWithNewNode();
- controller.AddVFXModel(mousePosition, newModel);
- newModel.SetSettingValue("m_Subgraph", references.First());
- //TODO add to picked groupnode
- e.StopPropagation();
- }
- }
- else if (!controller.model.isSubgraph) //can't drag a vfx subgraph block in a subgraph operator or a subgraph block
- {
- var droppedBlocks = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>();
- VisualEffectSubgraphBlock droppedBlock = droppedBlocks.FirstOrDefault();
- if (droppedBlock != null)
- {
- Vector2 mousePosition = contentViewContainer.WorldToLocal(e.mousePosition);
- VFXContextType contextKind = droppedBlocks.First().GetResource().GetOrCreateGraph().children.OfType<VFXBlockSubgraphContext>().First().compatibleContextType;
- VFXModelDescriptor<VFXContext> contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicInitialize));
- if ((contextKind & VFXContextType.Update) == VFXContextType.Update)
- contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicUpdate));
- else if ((contextKind & VFXContextType.Spawner) == VFXContextType.Spawner)
- contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXBasicSpawner));
- else if ((contextKind & VFXContextType.Output) == VFXContextType.Output)
- contextType = VFXLibrary.GetContexts().First(t => t.modelType == typeof(VFXPlanarPrimitiveOutput) && t.model.taskType == VFXTaskType.ParticleQuadOutput);
- UpdateSelectionWithNewNode();
- VFXContext ctx = controller.AddVFXContext(mousePosition, contextType);
- VFXModel newModel = VFXSubgraphBlock.CreateInstance<VFXSubgraphBlock>();
- newModel.SetSettingValue("m_Subgraph", droppedBlocks.First());
- UpdateSelectionWithNewNode();
- ctx.AddChild(newModel);
- //TODO add to picked groupnode
- e.StopPropagation();
- }
- }
- }
- }
- public void AssetMoved()
- {
- foreach (var item in this.Query<VFXNodeUI>().ToList())
- {
- item.AssetMoved();
- }
- }
- VFXEdgeDragInfo m_EdgeDragInfo;
- public void StartEdgeDragInfo(VFXDataAnchor draggerAnchor, VFXDataAnchor overAnchor)
- {
- if (m_EdgeDragInfo == null)
- {
- m_EdgeDragInfo = new VFXEdgeDragInfo(this);
- Add(m_EdgeDragInfo);
- m_EdgeDragInfo.style.display = DisplayStyle.None;
- }
- m_EdgeDragInfo.StartEdgeDragInfo(draggerAnchor, overAnchor);
- }
- public void StopEdgeDragInfo()
- {
- if (m_EdgeDragInfo != null)
- m_EdgeDragInfo.StopEdgeDragInfo();
- }
- public void DuplicateBlackboardFieldSelection()
- {
- foreach (var blackboardField in selection.OfType<VFXBlackboardField>())
- {
- DuplicateBlackboardField(blackboardField);
- }
- m_Controller.graph.SetExpressionValueDirty();
- }
- private void DuplicateBlackBoardCategorySelection()
- {
- foreach (var blackboardCategory in selection.OfType<VFXBlackboardCategory>())
- {
- var newCategory = blackboard.AddCategory(blackboardCategory.title);
- var parameters = blackboardCategory
- .Children()
- .OfType<VFXBlackboardRow>()
- .Select(x => DuplicateBlackboardField(x.field))
- .ToList();
- parameters.ForEach(x => x.model.category = newCategory.title);
- newCategory.SyncParameters(new HashSet<VFXParameterController>(parameters));
- }
- }
- private VFXParameterController DuplicateBlackboardField(VFXBlackboardField blackboardField)
- {
- var copyName = blackboardField.controller.MakeNameUnique(blackboardField.controller.exposedName);
- var newVfxParameter = VFXParameter.Duplicate(copyName, blackboardField.controller.model);
- controller.AddVFXModel(Vector2.zero, newVfxParameter);
- bool groupChanged = false;
- controller.SyncControllerFromModel(ref groupChanged);
- var newParameterController = blackboard.controller.parameterControllers.Single(x => x.model == newVfxParameter);
- if (blackboardField.controller.spaceableAndMasterOfSpace)
- {
- newParameterController.space = blackboardField.controller.space;
- }
- return newParameterController;
- }
- }
- }
|