SceneComponent.cpp 188 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <functional>
  9. #include <QAction>
  10. #include <QApplication>
  11. #include <QClipboard>
  12. #include <QKeyEvent>
  13. #include <QGraphicsItem>
  14. #include <QGraphicsSceneEvent>
  15. #include <QGraphicsView>
  16. #include <QScreen>
  17. #include <QMimeData>
  18. #include <AzCore/Casting/numeric_cast.h>
  19. #include <AzCore/Component/ComponentApplicationBus.h>
  20. #include <AzCore/Component/EntityUtils.h>
  21. #include <AzCore/Serialization/Utils.h>
  22. #include <AzCore/std/sort.h>
  23. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  24. #include <AzToolsFramework/Entity/EditorEntityHelpers.h>
  25. #include <Components/SceneComponent.h>
  26. #include <Components/BookmarkManagerComponent.h>
  27. #include <Components/BookmarkAnchor/BookmarkAnchorComponent.h>
  28. #include <Components/Connections/ConnectionComponent.h>
  29. #include <Components/GridComponent.h>
  30. #include <Components/Nodes/NodeComponent.h>
  31. #include <Components/SceneMemberComponent.h>
  32. #include <GraphCanvas/GraphCanvasBus.h>
  33. #include <GraphCanvas/Components/LayerBus.h>
  34. #include <GraphCanvas/Components/Nodes/Comment/CommentBus.h>
  35. #include <GraphCanvas/Components/Nodes/NodeTitleBus.h>
  36. #include <GraphCanvas/Components/Nodes/NodeUIBus.h>
  37. #include <GraphCanvas/Components/Nodes/Wrapper/WrapperNodeBus.h>
  38. #include <GraphCanvas/Components/PersistentIdBus.h>
  39. #include <GraphCanvas/Components/Slots/SlotBus.h>
  40. #include <GraphCanvas/Components/VisualBus.h>
  41. #include <GraphCanvas/Editor/GraphCanvasProfiler.h>
  42. #include <GraphCanvas/Editor/GraphModelBus.h>
  43. #include <GraphCanvas/Styling/Parser.h>
  44. #include <GraphCanvas/tools.h>
  45. #include <GraphCanvas/Types/GraphCanvasGraphSerialization.h>
  46. #include <GraphCanvas/Widgets/EditorContextMenu/ContextMenuActions/ContextMenuAction.h>
  47. #include <GraphCanvas/Widgets/GraphCanvasGraphicsView/GraphCanvasGraphicsView.h>
  48. #include <GraphCanvas/Widgets/GraphCanvasMimeContainer.h>
  49. #include <GraphCanvas/Widgets/MimeEvents/CreateSplicingNodeMimeEvent.h>
  50. #include <GraphCanvas/Utils/ConversionUtils.h>
  51. #include <GraphCanvas/Utils/QtVectorMath.h>
  52. namespace GraphCanvas
  53. {
  54. ////////////////
  55. // SceneHelper
  56. ////////////////
  57. void SceneHelper::SetSceneId(const AZ::EntityId& sceneId)
  58. {
  59. m_sceneId = sceneId;
  60. }
  61. const AZ::EntityId& SceneHelper::GetSceneId() const
  62. {
  63. return m_sceneId;
  64. }
  65. void SceneHelper::SetEditorId(const EditorId& editorId)
  66. {
  67. m_editorId = editorId;
  68. OnEditorIdSet();
  69. }
  70. const EditorId& SceneHelper::GetEditorId() const
  71. {
  72. return m_editorId;
  73. }
  74. void SceneHelper::OnEditorIdSet()
  75. {
  76. }
  77. ////////////////////////////
  78. // MimeDelegateSceneHelper
  79. ////////////////////////////
  80. void MimeDelegateSceneHelper::Activate()
  81. {
  82. m_pushedUndoBlock = false;
  83. m_enableConnectionSplicing = false;
  84. m_spliceTimer.setInterval(500);
  85. m_spliceTimer.setSingleShot(true);
  86. QObject::connect(&m_spliceTimer, &QTimer::timeout, [this]() { OnTrySplice(); });
  87. SceneMimeDelegateHandlerRequestBus::Handler::BusConnect(GetSceneId());
  88. SceneMimeDelegateRequestBus::Event(GetSceneId(), &SceneMimeDelegateRequests::AddDelegate, GetSceneId());
  89. m_nudgingController.SetGraphId(GetSceneId());
  90. }
  91. void MimeDelegateSceneHelper::Deactivate()
  92. {
  93. SceneMimeDelegateRequestBus::Event(GetSceneId(), &SceneMimeDelegateRequests::RemoveDelegate, GetSceneId());
  94. SceneMimeDelegateHandlerRequestBus::Handler::BusDisconnect();
  95. }
  96. void MimeDelegateSceneHelper::SetMimeType(const char* mimeType)
  97. {
  98. m_mimeType = mimeType;
  99. }
  100. const QString& MimeDelegateSceneHelper::GetMimeType() const
  101. {
  102. return m_mimeType;
  103. }
  104. bool MimeDelegateSceneHelper::HasMimeType() const
  105. {
  106. return !m_mimeType.isEmpty();
  107. }
  108. bool MimeDelegateSceneHelper::IsInterestedInMimeData(const AZ::EntityId& graphId, const QMimeData* mimeData)
  109. {
  110. bool isInterested = HasMimeType() && mimeData->hasFormat(GetMimeType());
  111. m_enableConnectionSplicing = false;
  112. if (isInterested)
  113. {
  114. // Need a copy since we are going to try to use
  115. // this event not in response to a movement, but in response to a timeout.
  116. m_splicingData = mimeData->data(GetMimeType());
  117. GraphCanvasMimeContainer mimeContainer;
  118. if (mimeContainer.FromBuffer(m_splicingData.constData(), m_splicingData.size()))
  119. {
  120. isInterested = !mimeContainer.m_mimeEvents.empty();
  121. for (GraphCanvas::GraphCanvasMimeEvent* mimeEvent : mimeContainer.m_mimeEvents)
  122. {
  123. if (!mimeEvent->CanGraphHandleEvent(graphId))
  124. {
  125. isInterested = false;
  126. break;
  127. }
  128. }
  129. // Splicing only makes sense when we have a single node.
  130. if (isInterested
  131. && mimeContainer.m_mimeEvents.size() == 1
  132. && azrtti_istypeof<CreateSplicingNodeMimeEvent>(mimeContainer.m_mimeEvents.front()))
  133. {
  134. m_enableConnectionSplicing = true;
  135. AZ_Error("GraphCanvas", !m_splicingNode.IsValid(), "Splicing node not properly invalidated in between interest calls.");
  136. m_splicingNode.SetInvalid();
  137. m_splicingPath = QPainterPath();
  138. }
  139. else
  140. {
  141. m_splicingData.clear();
  142. }
  143. }
  144. else
  145. {
  146. isInterested = false;
  147. }
  148. if (!isInterested)
  149. {
  150. m_splicingData.clear();
  151. }
  152. }
  153. return isInterested;
  154. }
  155. void MimeDelegateSceneHelper::HandleMove(const AZ::EntityId& /*sceneId*/, const QPointF& dragPoint, const QMimeData* /*mimeData*/)
  156. {
  157. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  158. bool enableSplicing = false;
  159. AssetEditorSettingsRequestBus::EventResult(enableSplicing, GetEditorId(), &AssetEditorSettingsRequests::IsDropConnectionSpliceEnabled);
  160. if (m_splicingNode.IsValid() || !m_splicingPath.isEmpty())
  161. {
  162. if (!m_splicingPath.contains(dragPoint))
  163. {
  164. CancelSplice();
  165. }
  166. else if (m_splicingNode.IsValid())
  167. {
  168. PushUndoBlock();
  169. GeometryRequestBus::Event(m_splicingNode, &GeometryRequests::SetPosition, ConversionUtils::QPointToVector(dragPoint) + m_positionOffset);
  170. PopUndoBlock();
  171. }
  172. }
  173. AZ::EntityId targetId;
  174. AZ::Vector2 targetVector(aznumeric_cast<float>(dragPoint.x()), aznumeric_cast<float>(dragPoint.y()));
  175. AZStd::vector< AZ::EntityId > entitiesAtCursor;
  176. SceneRequestBus::EventResult(entitiesAtCursor, GetSceneId(), &SceneRequests::GetEntitiesAt, targetVector);
  177. AZ::EntityId groupTarget;
  178. AZStd::unordered_set< AZ::EntityId > parentGroups;
  179. int groupHitCounter = 0;
  180. int connectionHitCounter = 0;
  181. for (const auto& entityId : entitiesAtCursor)
  182. {
  183. // Handle targeting for connections
  184. if (GraphUtils::IsConnection(entityId))
  185. {
  186. ++connectionHitCounter;
  187. QGraphicsItem* connectionObject = nullptr;
  188. VisualRequestBus::EventResult(connectionObject, entityId, &VisualRequests::AsGraphicsItem);
  189. m_splicingPath = connectionObject->shape();
  190. targetId = entityId;
  191. }
  192. // Handle Targeting for Groups
  193. else if (GraphUtils::IsNodeGroup(entityId))
  194. {
  195. // If our this element is already in the list of parent nodes it's fine, we have a more specific group to drop to.
  196. if (parentGroups.find(entityId) != parentGroups.end())
  197. {
  198. continue;
  199. }
  200. // Otherwise, we want to walk up out group parent, and if we find out
  201. AZ::EntityId groupId = entityId;
  202. parentGroups.clear();
  203. bool isMoreSpecificGroupTarget = false;
  204. while (groupId.IsValid())
  205. {
  206. parentGroups.insert(groupId);
  207. GroupableSceneMemberRequestBus::EventResult(groupId, groupId, &GroupableSceneMemberRequests::GetGroupId);
  208. if (groupId == groupTarget && groupTarget.IsValid())
  209. {
  210. isMoreSpecificGroupTarget = true;
  211. }
  212. }
  213. if (isMoreSpecificGroupTarget)
  214. {
  215. groupTarget = entityId;
  216. continue;
  217. }
  218. // Set our group target, and update the number of unique group chains we've seen.
  219. // If we see more then one, we don't want to do anything with this.
  220. groupTarget = entityId;
  221. ++groupHitCounter;
  222. }
  223. }
  224. // Only want to do the splicing if it's unambiguous which thing they are over.
  225. if ((enableSplicing || m_enableConnectionSplicing) && !m_splicingNode.IsValid())
  226. {
  227. if (connectionHitCounter == 1)
  228. {
  229. if (m_targetConnection != targetId)
  230. {
  231. m_targetConnection = targetId;
  232. m_targetPosition = dragPoint;
  233. StateController<RootGraphicsItemDisplayState>* stateController = nullptr;
  234. RootGraphicsItemRequestBus::EventResult(stateController, m_targetConnection, &RootGraphicsItemRequests::GetDisplayStateStateController);
  235. if (stateController)
  236. {
  237. m_displayStateStateSetter.AddStateController(stateController);
  238. m_displayStateStateSetter.SetState(RootGraphicsItemDisplayState::Preview);
  239. }
  240. AZStd::chrono::milliseconds spliceDuration(500);
  241. AssetEditorSettingsRequestBus::EventResult(spliceDuration, GetEditorId(), &AssetEditorSettingsRequests::GetDropConnectionSpliceTime);
  242. m_spliceTimer.stop();
  243. m_spliceTimer.setInterval(aznumeric_cast<int>(spliceDuration.count()));
  244. m_spliceTimer.start();
  245. }
  246. }
  247. else
  248. {
  249. if (m_targetConnection.IsValid())
  250. {
  251. m_displayStateStateSetter.ResetStateSetter();
  252. m_targetConnection.SetInvalid();
  253. m_spliceTimer.stop();
  254. }
  255. if (connectionHitCounter > 0)
  256. {
  257. m_splicingPath = QPainterPath();
  258. }
  259. }
  260. }
  261. if (groupTarget.IsValid() && groupHitCounter == 1)
  262. {
  263. if (groupTarget != m_groupTarget)
  264. {
  265. m_groupTargetStateSetter.ResetStateSetter();
  266. m_groupTarget = groupTarget;
  267. StateController<RootGraphicsItemDisplayState>* stateController = nullptr;
  268. RootGraphicsItemRequestBus::EventResult(stateController, m_groupTarget, &RootGraphicsItemRequests::GetDisplayStateStateController);
  269. m_groupTargetStateSetter.AddStateController(stateController);
  270. m_groupTargetStateSetter.SetState(RootGraphicsItemDisplayState::GroupHighlight);
  271. }
  272. }
  273. else
  274. {
  275. m_groupTarget.SetInvalid();
  276. m_groupTargetStateSetter.ResetStateSetter();
  277. }
  278. }
  279. void MimeDelegateSceneHelper::HandleDrop(const AZ::EntityId& /*sceneId*/, const QPointF& dropPoint, const QMimeData* mimeData)
  280. {
  281. GRAPH_CANVAS_PROFILE_FUNCTION();
  282. // Once we finalize the node, we want to release the undo state, and push a new undo.
  283. ScopedGraphUndoBatch undoBatch(GetSceneId());
  284. m_spliceTimer.stop();
  285. m_displayStateStateSetter.ResetStateSetter();
  286. if (m_splicingNode.IsValid())
  287. {
  288. SceneRequestBus::Event(GetSceneId(), &SceneRequests::ClearSelection);
  289. SceneMemberUIRequestBus::Event(m_splicingNode, &SceneMemberUIRequests::SetSelected, true);
  290. m_nudgingController.FinalizeNudging();
  291. m_lastCreationGroup.clear();
  292. m_lastCreationGroup.insert(m_splicingNode);
  293. m_splicingData.clear();
  294. m_splicingNode.SetInvalid();
  295. m_targetConnection.SetInvalid();
  296. m_splicingPath = QPainterPath();
  297. AssignLastCreationToGroup();
  298. return;
  299. }
  300. if (!mimeData->hasFormat(GetMimeType()))
  301. {
  302. AZ_Error("SceneMimeDelegate", false, "Handling an event that does not meet our Mime requirements");
  303. return;
  304. }
  305. QByteArray arrayData = mimeData->data(GetMimeType());
  306. GraphCanvasMimeContainer mimeContainer;
  307. if (!mimeContainer.FromBuffer(arrayData.constData(), arrayData.size()) || mimeContainer.m_mimeEvents.empty())
  308. {
  309. return;
  310. }
  311. bool success = false;
  312. AZ::Vector2 sceneMousePoint = AZ::Vector2(aznumeric_cast<float>(dropPoint.x()), aznumeric_cast<float>(dropPoint.y()));
  313. AZ::Vector2 sceneDropPoint = sceneMousePoint;
  314. QGraphicsScene* graphicsScene = nullptr;
  315. SceneRequestBus::EventResult(graphicsScene, GetSceneId(), &SceneRequests::AsQGraphicsScene);
  316. if (graphicsScene)
  317. {
  318. graphicsScene->blockSignals(true);
  319. }
  320. SceneRequestBus::Event(GetSceneId(), &SceneRequests::ClearSelection);
  321. m_lastCreationGroup.clear();
  322. for (GraphCanvasMimeEvent* mimeEvent : mimeContainer.m_mimeEvents)
  323. {
  324. if (mimeEvent->ExecuteEvent(sceneMousePoint, sceneDropPoint, GetSceneId()))
  325. {
  326. success = true;
  327. }
  328. }
  329. if (success)
  330. {
  331. SceneNotificationBus::Event(GetSceneId(), &SceneNotifications::PostCreationEvent);
  332. AssignLastCreationToGroup();
  333. }
  334. if (graphicsScene)
  335. {
  336. graphicsScene->blockSignals(false);
  337. emit graphicsScene->selectionChanged();
  338. }
  339. }
  340. void MimeDelegateSceneHelper::HandleLeave(const AZ::EntityId& /*sceneId*/, const QMimeData* /*mimeData*/)
  341. {
  342. CancelSplice();
  343. }
  344. void MimeDelegateSceneHelper::SignalNodeCreated(const NodeId& nodeId)
  345. {
  346. m_lastCreationGroup.insert(nodeId);
  347. }
  348. void MimeDelegateSceneHelper::OnTrySplice()
  349. {
  350. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  351. if (m_targetConnection.IsValid())
  352. {
  353. GraphCanvasMimeContainer mimeContainer;
  354. if (mimeContainer.FromBuffer(m_splicingData.constData(), m_splicingData.size()))
  355. {
  356. if (mimeContainer.m_mimeEvents.empty())
  357. {
  358. return;
  359. }
  360. ConnectionRequestBus::EventResult(m_spliceSource, m_targetConnection, &ConnectionRequests::GetSourceEndpoint);
  361. ConnectionRequestBus::EventResult(m_spliceTarget, m_targetConnection, &ConnectionRequests::GetTargetEndpoint);
  362. m_opportunisticSpliceRemovals.clear();
  363. CreateSplicingNodeMimeEvent* mimeEvent = azrtti_cast<CreateSplicingNodeMimeEvent*>(mimeContainer.m_mimeEvents.front());
  364. if (mimeEvent)
  365. {
  366. PushUndoBlock();
  367. m_splicingNode = mimeEvent->CreateSplicingNode(GetSceneId());
  368. if (m_splicingNode.IsValid())
  369. {
  370. SceneRequestBus::Event(GetSceneId(), &SceneRequests::AddNode, m_splicingNode, ConversionUtils::QPointToVector(m_targetPosition), false);
  371. ConnectionSpliceConfig connectionSpliceConfig;
  372. connectionSpliceConfig.m_allowOpportunisticConnections = true;
  373. bool allowNode = GraphUtils::SpliceNodeOntoConnection(m_splicingNode, m_targetConnection, connectionSpliceConfig);
  374. if (!allowNode)
  375. {
  376. AZStd::unordered_set<AZ::EntityId> deleteIds = { m_splicingNode };
  377. SceneRequestBus::Event(GetSceneId(), &SceneRequests::Delete, deleteIds);
  378. m_splicingNode.SetInvalid();
  379. }
  380. else
  381. {
  382. m_displayStateStateSetter.ResetStateSetter();
  383. m_opportunisticSpliceRemovals = connectionSpliceConfig.m_opportunisticSpliceResult.m_removedConnections;
  384. StateController<RootGraphicsItemDisplayState>* stateController = nullptr;
  385. RootGraphicsItemRequestBus::EventResult(stateController, m_splicingNode, &RootGraphicsItemRequests::GetDisplayStateStateController);
  386. m_displayStateStateSetter.AddStateController(stateController);
  387. AZStd::vector< AZ::EntityId > slotIds;
  388. NodeRequestBus::EventResult(slotIds, m_splicingNode, &NodeRequests::GetSlotIds);
  389. AZ::Vector2 centerPoint(0,0);
  390. int totalSamples = 0;
  391. for (const AZ::EntityId& slotId : slotIds)
  392. {
  393. AZStd::vector< AZ::EntityId > connectionIds;
  394. SlotRequestBus::EventResult(connectionIds, slotId, &SlotRequests::GetConnections);
  395. if (!connectionIds.empty())
  396. {
  397. QPointF slotPosition;
  398. SlotUIRequestBus::EventResult(slotPosition, slotId, &SlotUIRequests::GetConnectionPoint);
  399. centerPoint += ConversionUtils::QPointToVector(slotPosition);
  400. ++totalSamples;
  401. for (const AZ::EntityId& connectionId : connectionIds)
  402. {
  403. stateController = nullptr;
  404. RootGraphicsItemRequestBus::EventResult(stateController, connectionId, &RootGraphicsItemRequests::GetDisplayStateStateController);
  405. m_displayStateStateSetter.AddStateController(stateController);
  406. }
  407. }
  408. }
  409. if (totalSamples > 0)
  410. {
  411. centerPoint /= aznumeric_cast<float>(totalSamples);
  412. }
  413. m_positionOffset = ConversionUtils::QPointToVector(m_targetPosition) - centerPoint;
  414. GeometryRequestBus::Event(m_splicingNode, &GeometryRequests::SetPosition, m_positionOffset + ConversionUtils::QPointToVector(m_targetPosition));
  415. m_displayStateStateSetter.SetState(RootGraphicsItemDisplayState::Preview);
  416. AnimatedPulseConfiguration pulseConfiguration;
  417. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  418. pulseConfiguration.m_durationSec = 0.35f;
  419. pulseConfiguration.m_enableGradient = true;
  420. QGraphicsItem* item = nullptr;
  421. SceneMemberUIRequestBus::EventResult(item, m_splicingNode, &SceneMemberUIRequests::GetRootGraphicsItem);
  422. if (item)
  423. {
  424. pulseConfiguration.m_zValue = item->zValue() - 1;
  425. }
  426. const int k_squaresToPulse = 4;
  427. SceneRequestBus::Event(GetSceneId(), &SceneRequests::CreatePulseAroundSceneMember, m_splicingNode, k_squaresToPulse, pulseConfiguration);
  428. bool enableNudging = false;
  429. AssetEditorSettingsRequestBus::EventResult(enableNudging, GetEditorId(), &AssetEditorSettingsRequests::IsNodeNudgingEnabled);
  430. if (enableNudging)
  431. {
  432. AZStd::unordered_set< NodeId > elementIds = { m_splicingNode };
  433. m_nudgingController.StartNudging(elementIds);
  434. }
  435. }
  436. }
  437. PopUndoBlock();
  438. }
  439. }
  440. }
  441. }
  442. void MimeDelegateSceneHelper::CancelSplice()
  443. {
  444. m_displayStateStateSetter.ResetStateSetter();
  445. m_spliceTimer.stop();
  446. m_splicingPath = QPainterPath();
  447. m_nudgingController.CancelNudging();
  448. if (m_splicingNode.IsValid())
  449. {
  450. PushUndoBlock();
  451. AZStd::unordered_set< AZ::EntityId > deleteIds = { m_splicingNode };
  452. SceneRequestBus::Event(GetSceneId(), &SceneRequests::Delete, deleteIds);
  453. m_splicingNode.SetInvalid();
  454. AZ::EntityId connectionId;
  455. SlotRequestBus::EventResult(connectionId, m_spliceSource.GetSlotId(), &SlotRequests::CreateConnectionWithEndpoint, m_spliceTarget);
  456. AZ_Error("GraphCanvas", connectionId.IsValid(), "Failed to recreate a connection after unsplicing a spliced node.");
  457. for (const ConnectionEndpoints& removedConnection : m_opportunisticSpliceRemovals)
  458. {
  459. AZ::EntityId opportunisticConnectionId;
  460. SlotRequestBus::EventResult(opportunisticConnectionId, removedConnection.m_sourceEndpoint.GetSlotId(), &SlotRequests::CreateConnectionWithEndpoint, removedConnection.m_targetEndpoint);
  461. AZ_Error("GraphCanvas", opportunisticConnectionId.IsValid(), "Failed to recreate a connection after unsplicing a spliced node.");
  462. }
  463. m_opportunisticSpliceRemovals.clear();
  464. PopUndoBlock();
  465. }
  466. }
  467. void MimeDelegateSceneHelper::PushUndoBlock()
  468. {
  469. if (!m_pushedUndoBlock)
  470. {
  471. GraphModelRequestBus::Event(GetSceneId(), &GraphModelRequests::RequestPushPreventUndoStateUpdate);
  472. m_pushedUndoBlock = true;
  473. }
  474. }
  475. void MimeDelegateSceneHelper::PopUndoBlock()
  476. {
  477. if (m_pushedUndoBlock)
  478. {
  479. m_pushedUndoBlock = false;
  480. GraphModelRequestBus::Event(GetSceneId(), &GraphModelRequests::RequestPopPreventUndoStateUpdate);
  481. }
  482. }
  483. void MimeDelegateSceneHelper::AssignLastCreationToGroup()
  484. {
  485. if (m_groupTarget.IsValid() && !m_lastCreationGroup.empty())
  486. {
  487. AZStd::unordered_set< NodeId > filteredCreationGroup;
  488. for (const auto& createdNode : m_lastCreationGroup)
  489. {
  490. if (GraphUtils::IsNodeWrapped(createdNode))
  491. {
  492. continue;
  493. }
  494. filteredCreationGroup.insert(createdNode);
  495. }
  496. if (!filteredCreationGroup.empty())
  497. {
  498. NodeGroupRequests* nodeGroupRequests = NodeGroupRequestBus::FindFirstHandler(m_groupTarget);
  499. if (nodeGroupRequests)
  500. {
  501. nodeGroupRequests->AddElementsToGroup(filteredCreationGroup);
  502. const bool growGroupOnly = true;
  503. nodeGroupRequests->ResizeGroupToElements(growGroupOnly);
  504. }
  505. }
  506. }
  507. m_groupTarget.SetInvalid();
  508. m_groupTargetStateSetter.ResetStateSetter();
  509. }
  510. ///////////////////////
  511. // GestureSceneHelper
  512. ///////////////////////
  513. void GestureSceneHelper::Activate()
  514. {
  515. m_shakeCounter = 0;
  516. m_trackingTarget.SetInvalid();
  517. m_hasDirection = false;
  518. m_timer.setSingleShot(true);
  519. QObject::connect(&m_timer, &QTimer::timeout, [this]() { ResetTracker(); });
  520. }
  521. void GestureSceneHelper::Deactivate()
  522. {
  523. GeometryNotificationBus::Handler::BusDisconnect();
  524. SceneNotificationBus::Handler::BusDisconnect();
  525. AZ::SystemTickBus::Handler::BusDisconnect();
  526. }
  527. void GestureSceneHelper::TrackElement(const AZ::EntityId& elementId)
  528. {
  529. if (m_trackShake)
  530. {
  531. AZ_Error("GraphCanvas", !m_trackingTarget.IsValid(), "Trying to track a second target for gestures while still tracking the first.");
  532. if (GeometryNotificationBus::Handler::BusIsConnected())
  533. {
  534. GeometryNotificationBus::Handler::BusDisconnect();
  535. }
  536. GeometryNotificationBus::Handler::BusConnect(elementId);
  537. m_trackingTarget = elementId;
  538. m_shakeCounter = 0;
  539. m_hasDirection = false;
  540. m_currentAnchor = QCursor::pos();
  541. m_lastPoint = m_currentAnchor;
  542. SceneNotificationBus::Handler::BusConnect(GetSceneId());
  543. }
  544. }
  545. void GestureSceneHelper::ResetTracker()
  546. {
  547. m_hasDirection = false;
  548. m_shakeCounter = 0;
  549. }
  550. void GestureSceneHelper::StopTrack()
  551. {
  552. SceneNotificationBus::Handler::BusDisconnect();
  553. GeometryNotificationBus::Handler::BusDisconnect();
  554. m_trackingTarget.SetInvalid();
  555. }
  556. void GestureSceneHelper::OnPositionChanged(const AZ::EntityId& itemId, const AZ::Vector2& position)
  557. {
  558. AZ_UNUSED(itemId);
  559. AZ_UNUSED(position);
  560. QPointF currentPoint = QCursor::pos();
  561. QPointF currentDirection = currentPoint - m_lastPoint;
  562. float length = QtVectorMath::GetLength(currentDirection);
  563. if (length >= m_movementTolerance)
  564. {
  565. AZ::Vector2 currentVector = ConversionUtils::QPointToVector(currentDirection);
  566. currentVector.Normalize();
  567. AZ::Vector2 anchorVector = ConversionUtils::QPointToVector(currentPoint - m_currentAnchor);
  568. anchorVector.Normalize();
  569. if (m_hasDirection)
  570. {
  571. // Want to keep track of our current moving direction to see if we switched directions
  572. // Also need to keep track of our ovverall moving direction to see if we strayed too far off course.
  573. float currentDotProduct = m_lastDirection.Dot(currentVector);
  574. float anchorDotProduct = m_lastDirection.Dot(anchorVector);
  575. float totalLengthMoved = ConversionUtils::QPointToVector(m_currentAnchor - m_lastPoint).GetLength();
  576. // This means we pivoted.
  577. if (currentDotProduct <= -m_straightnessPercent && totalLengthMoved >= m_minimumDistance)
  578. {
  579. m_shakeCounter++;
  580. if (m_shakeCounter >= m_shakeThreshold)
  581. {
  582. if (!AZ::SystemTickBus::Handler::BusIsConnected())
  583. {
  584. AZ::SystemTickBus::Handler::BusConnect();
  585. }
  586. m_handleShakeAction = true;
  587. ResetTracker();
  588. }
  589. m_lastDirection = currentVector;
  590. m_currentAnchor = m_lastPoint;
  591. }
  592. else if (anchorDotProduct <= m_straightnessPercent)
  593. {
  594. ResetTracker();
  595. m_currentAnchor = currentPoint;
  596. }
  597. }
  598. else
  599. {
  600. m_hasDirection = true;
  601. m_lastDirection = currentVector;
  602. m_shakeCounter = 0;
  603. m_timer.stop();
  604. m_timer.start();
  605. }
  606. m_lastPoint = currentPoint;
  607. }
  608. }
  609. void GestureSceneHelper::OnSettingsChanged()
  610. {
  611. // We want to make our movement stuff relative so it deals with different resolutions reasonably well.
  612. // This does not however deal with different monitors with different displays, since that is just
  613. // sadness incarnate.
  614. //
  615. // Also currently doesn't handle screen resolution changing. Probably a signal for that though.
  616. float movementToleranceAmount = 0.0f;
  617. AssetEditorSettingsRequestBus::EventResult(movementToleranceAmount, GetEditorId(), &AssetEditorSettingsRequests::GetMinimumShakePercent);
  618. float precisionTolerance = 0.0f;
  619. AssetEditorSettingsRequestBus::EventResult(precisionTolerance, GetEditorId(), &AssetEditorSettingsRequests::GetShakeDeadZonePercent);
  620. QScreen* screen = QApplication::primaryScreen();
  621. QSize size = screen->size();
  622. QPointF dimension(size.width(), size.height());
  623. float length = QtVectorMath::GetLength(dimension);
  624. m_movementTolerance = length * precisionTolerance;
  625. m_minimumDistance = length * movementToleranceAmount;
  626. AZStd::chrono::milliseconds duration(500);
  627. AssetEditorSettingsRequestBus::EventResult(duration, GetEditorId(), &AssetEditorSettingsRequests::GetMaximumShakeDuration);
  628. m_timer.setInterval(aznumeric_cast<int>(duration.count()));
  629. AssetEditorSettingsRequestBus::EventResult(m_trackShake, GetEditorId(), &AssetEditorSettingsRequests::IsShakeToDespliceEnabled);
  630. AssetEditorSettingsRequestBus::EventResult(m_shakeThreshold, GetEditorId(), &AssetEditorSettingsRequests::GetShakesToDesplice);
  631. AssetEditorSettingsRequestBus::EventResult(m_straightnessPercent, GetEditorId(), &AssetEditorSettingsRequests::GetShakeStraightnessPercent);
  632. }
  633. void GestureSceneHelper::OnSystemTick()
  634. {
  635. if (m_handleShakeAction)
  636. {
  637. m_handleShakeAction = false;
  638. HandleDesplice();
  639. }
  640. AZ::SystemTickBus::Handler::BusDisconnect();
  641. }
  642. void GestureSceneHelper::OnEditorIdSet()
  643. {
  644. OnSettingsChanged();
  645. }
  646. void GestureSceneHelper::HandleDesplice()
  647. {
  648. ScopedGraphUndoBlocker undoBlocker(GetSceneId());
  649. bool despliced = false;
  650. AZStd::vector< AZ::EntityId > selectedItems;
  651. SceneRequestBus::EventResult(selectedItems, GetSceneId(), &SceneRequests::GetSelectedItems);
  652. AZStd::unordered_set< AZ::EntityId > nodeGroups;
  653. AZStd::unordered_set< NodeId > floatingNodeIds;
  654. for (const AZ::EntityId& selectedItem : selectedItems)
  655. {
  656. if (GraphUtils::IsNodeGroup(selectedItem))
  657. {
  658. nodeGroups.insert(selectedItem);
  659. floatingNodeIds.insert(selectedItem);
  660. }
  661. else if (GraphUtils::IsNode(selectedItem) || GraphUtils::IsCollapsedNodeGroup(selectedItem))
  662. {
  663. floatingNodeIds.insert(selectedItem);
  664. }
  665. }
  666. SubGraphParsingConfig subGraphParseConfig;
  667. for (const AZ::EntityId& nodeGroup : nodeGroups)
  668. {
  669. AZStd::vector< AZ::EntityId > groupedItems;
  670. NodeGroupRequestBus::Event(nodeGroup, &NodeGroupRequests::FindGroupedElements, groupedItems);
  671. for (const AZ::EntityId& groupedItem : groupedItems)
  672. {
  673. if (GraphUtils::IsNode(groupedItem)
  674. || GraphUtils::IsCollapsedNodeGroup(groupedItem))
  675. {
  676. floatingNodeIds.erase(groupedItem);
  677. }
  678. }
  679. bool causeBurst = false;
  680. SubGraphParsingResult subGraphResult = GraphUtils::ParseSceneMembersIntoSubGraphs(groupedItems, subGraphParseConfig);
  681. for (const GraphSubGraph& subGraph : subGraphResult.m_subGraphs)
  682. {
  683. if (subGraph.m_entryConnections.empty() && subGraph.m_exitConnections.empty())
  684. {
  685. continue;
  686. }
  687. causeBurst = true;
  688. GraphUtils::DetachSubGraphAndStitchConnections(subGraph);
  689. }
  690. if (causeBurst)
  691. {
  692. despliced = true;
  693. AnimatedPulseConfiguration pulseConfiguration;
  694. pulseConfiguration.m_durationSec = 0.5;
  695. pulseConfiguration.m_enableGradient = true;
  696. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  697. QGraphicsItem* rootItem = nullptr;
  698. SceneMemberUIRequestBus::EventResult(rootItem, nodeGroup, &SceneMemberUIRequests::GetRootGraphicsItem);
  699. QRectF boundingArea;
  700. if (rootItem)
  701. {
  702. pulseConfiguration.m_zValue = rootItem->zValue() + 1;
  703. boundingArea = rootItem->sceneBoundingRect();
  704. }
  705. SceneRequestBus::Event(GetSceneId(), &SceneRequests::CreatePulseAroundArea, boundingArea, 3, pulseConfiguration);
  706. }
  707. }
  708. AZStd::vector< AZ::EntityId > floatingElements(floatingNodeIds.begin(), floatingNodeIds.end());
  709. SubGraphParsingResult subGraphResult = GraphUtils::ParseSceneMembersIntoSubGraphs(floatingElements, subGraphParseConfig);
  710. if (subGraphResult.m_subGraphs.size() == 1)
  711. {
  712. for (const GraphSubGraph& subGraph : subGraphResult.m_subGraphs)
  713. {
  714. if (subGraph.m_entryConnections.empty() && subGraph.m_exitConnections.empty())
  715. {
  716. continue;
  717. }
  718. GraphUtils::DetachSubGraphAndStitchConnections(subGraph);
  719. QRectF boundingRect;
  720. int maxZValue = 0;
  721. for (const AZ::EntityId& elementId : subGraph.m_containedNodes)
  722. {
  723. QGraphicsItem* item = nullptr;
  724. SceneMemberUIRequestBus::EventResult(item, elementId, &SceneMemberUIRequests::GetRootGraphicsItem);
  725. if (item)
  726. {
  727. if (item->zValue() > maxZValue)
  728. {
  729. maxZValue = aznumeric_cast<int>(item->zValue());
  730. }
  731. if (boundingRect.isEmpty())
  732. {
  733. boundingRect = item->sceneBoundingRect();
  734. }
  735. else
  736. {
  737. boundingRect |= item->sceneBoundingRect();
  738. }
  739. }
  740. }
  741. AnimatedPulseConfiguration pulseConfiguration;
  742. pulseConfiguration.m_durationSec = 0.5;
  743. pulseConfiguration.m_enableGradient = true;
  744. pulseConfiguration.m_zValue = maxZValue + 1;
  745. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  746. SceneRequestBus::Event(GetSceneId(), &SceneRequests::CreatePulseAroundArea, boundingRect, 3, pulseConfiguration);
  747. despliced = true;
  748. }
  749. }
  750. if (despliced)
  751. {
  752. SceneRequestBus::Event(GetSceneId(), &SceneRequests::SignalDesplice);
  753. }
  754. }
  755. ///////////////
  756. // Copy Utils
  757. ///////////////
  758. void SerializeToBuffer(const GraphSerialization& serializationTarget, AZStd::vector<char>& buffer)
  759. {
  760. AZ::SerializeContext* serializeContext = AZ::EntityUtils::GetApplicationSerializeContext();
  761. AZ::IO::ByteContainerStream<AZStd::vector<char>> stream(&buffer);
  762. AZ::Utils::SaveObjectToStream(stream, AZ::DataStream::ST_BINARY, &serializationTarget, serializeContext);
  763. }
  764. void SerializeToClipboard(const GraphSerialization& serializationTarget)
  765. {
  766. AZ_Error("Graph Canvas", !serializationTarget.GetSerializationKey().empty(), "Serialization Key not server for scene serialization. Cannot push to clipboard.");
  767. if (serializationTarget.GetSerializationKey().empty())
  768. {
  769. return;
  770. }
  771. AZStd::vector<char> buffer;
  772. SerializeToBuffer(serializationTarget, buffer);
  773. QMimeData* mime = new QMimeData();
  774. mime->setData(serializationTarget.GetSerializationKey().c_str(), QByteArray(buffer.cbegin(), static_cast<int>(buffer.size())));
  775. QClipboard* clipboard = QApplication::clipboard();
  776. clipboard->setMimeData(mime);
  777. }
  778. ///////////////////
  779. // SceneComponent
  780. ///////////////////
  781. constexpr unsigned int k_particleLimit = 250;
  782. void BuildEndpointMap(GraphData& graphData)
  783. {
  784. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  785. graphData.m_endpointMap.clear();
  786. for (auto& connectionEntity : graphData.m_connections)
  787. {
  788. auto* connection = connectionEntity ? AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(connectionEntity) : nullptr;
  789. if (connection)
  790. {
  791. graphData.m_endpointMap.emplace(connection->GetSourceEndpoint(), connection->GetTargetEndpoint());
  792. graphData.m_endpointMap.emplace(connection->GetTargetEndpoint(), connection->GetSourceEndpoint());
  793. }
  794. }
  795. }
  796. class GraphCanvasSceneDataEventHandler : public AZ::SerializeContext::IEventHandler
  797. {
  798. public:
  799. /// Called to rebuild the Endpoint map
  800. void OnWriteEnd(void* classPtr) override
  801. {
  802. auto* sceneData = reinterpret_cast<GraphData*>(classPtr);
  803. BuildEndpointMap((*sceneData));
  804. }
  805. };
  806. /////////////////////////////////
  807. // GraphCanvasConstructSaveData
  808. /////////////////////////////////
  809. bool SceneComponent::GraphCanvasConstructSaveData::VersionConverter(AZ::SerializeContext& serializeContext, AZ::SerializeContext::DataElementNode& classElement)
  810. {
  811. if (classElement.GetVersion() == 1)
  812. {
  813. AZ::Crc32 typeId = AZ_CRC_CE("Type");
  814. AZ::SerializeContext::DataElementNode* dataNode = classElement.FindSubElement(typeId);
  815. ConstructType constructType = ConstructType::Unknown;
  816. if (dataNode)
  817. {
  818. GraphCanvasConstructType deprecatedType = GraphCanvasConstructType::Unknown;
  819. dataNode->GetData(deprecatedType);
  820. if (deprecatedType == GraphCanvasConstructType::BlockCommentNode)
  821. {
  822. constructType = ConstructType::NodeGroup;
  823. }
  824. else if (deprecatedType == GraphCanvasConstructType::CommentNode)
  825. {
  826. constructType = ConstructType::CommentNode;
  827. }
  828. else if (deprecatedType == GraphCanvasConstructType::BookmarkAnchor)
  829. {
  830. constructType = ConstructType::BookmarkAnchor;
  831. }
  832. }
  833. classElement.RemoveElementByName(typeId);
  834. classElement.AddElementWithData(serializeContext, "Type", constructType);
  835. }
  836. return true;
  837. }
  838. ///////////////////
  839. // SceneComponent
  840. ///////////////////
  841. void SceneComponent::Reflect(AZ::ReflectContext* context)
  842. {
  843. GraphSerialization::Reflect(context);
  844. AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
  845. if (!serializeContext)
  846. {
  847. return;
  848. }
  849. serializeContext->Class<GraphData>()
  850. ->Version(2)
  851. ->EventHandler<GraphCanvasSceneDataEventHandler>()
  852. ->Field("m_nodes", &GraphData::m_nodes)
  853. ->Field("m_connections", &GraphData::m_connections)
  854. ->Field("m_userData", &GraphData::m_userData)
  855. ->Field("m_bookmarkAnchors", &GraphData::m_bookmarkAnchors)
  856. ;
  857. serializeContext->Class<GraphCanvasConstructSaveData>()
  858. ->Version(2, &GraphCanvasConstructSaveData::VersionConverter)
  859. ->Field("Type", &GraphCanvasConstructSaveData::m_constructType)
  860. ->Field("DataContainer", &GraphCanvasConstructSaveData::m_saveDataContainer)
  861. ;
  862. serializeContext->Class<ViewParams>()
  863. ->Version(1)
  864. ->Field("Scale", &ViewParams::m_scale)
  865. ->Field("AnchorX", &ViewParams::m_anchorPointX)
  866. ->Field("AnchorY", &ViewParams::m_anchorPointY)
  867. ;
  868. serializeContext->Class<SceneComponentSaveData>()
  869. ->Version(3)
  870. ->Field("Constructs", &SceneComponentSaveData::m_constructs)
  871. ->Field("ViewParams", &SceneComponentSaveData::m_viewParams)
  872. ->Field("BookmarkCounter", &SceneComponentSaveData::m_bookmarkCounter)
  873. ;
  874. serializeContext->Class<SceneComponent, GraphCanvasPropertyComponent>()
  875. ->Version(3)
  876. ->Field("SceneData", &SceneComponent::m_graphData)
  877. ->Field("ViewParams", &SceneComponent::m_viewParams)
  878. ;
  879. }
  880. SceneComponent::SceneComponent()
  881. : m_allowReset(false)
  882. , m_deleteCount(0)
  883. , m_dragSelectionType(DragSelectionType::OnRelease)
  884. , m_isLoading(false)
  885. , m_isPasting(false)
  886. , m_activateScene(true)
  887. , m_isDragSelecting(false)
  888. , m_originalPosition(0,0)
  889. , m_forceDragReleaseUndo(false)
  890. , m_isDraggingEntity(false)
  891. , m_isDraggingConnection(false)
  892. , m_enableSpliceTracking(false)
  893. , m_enableNodeDragConnectionSpliceTracking(false)
  894. , m_enableNodeDragCouplingTracking(false)
  895. , m_bookmarkCounter(0)
  896. {
  897. m_spliceTimer.setInterval(500);
  898. m_spliceTimer.setSingleShot(true);
  899. QObject::connect(&m_spliceTimer, &QTimer::timeout, [this]() { OnTrySplice(); });
  900. }
  901. SceneComponent::~SceneComponent()
  902. {
  903. DestroyItems(m_graphData.m_nodes);
  904. DestroyItems(m_graphData.m_connections);
  905. DestroyItems(m_graphData.m_bookmarkAnchors);
  906. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, m_grid);
  907. }
  908. void SceneComponent::Init()
  909. {
  910. GRAPH_CANVAS_PROFILE_FUNCTION();
  911. GraphCanvasPropertyComponent::Init();
  912. // Make the QGraphicsScene Ui element for managing Qt scene items
  913. m_graphicsSceneUi = AZStd::make_unique<GraphCanvasGraphicsScene>(*this);
  914. AZ::EntityBus::Handler::BusConnect(GetEntityId());
  915. AZ::Entity* gridEntity = GridComponent::CreateDefaultEntity();
  916. m_grid = gridEntity->GetId();
  917. InitItems(m_graphData.m_nodes);
  918. InitConnections();
  919. InitItems(m_graphData.m_bookmarkAnchors);
  920. // Grids needs to be active for the save information parsing to work correctly
  921. ActivateItems(AZStd::initializer_list<AZ::Entity*>{ AzToolsFramework::GetEntity(m_grid) });
  922. ////
  923. EntitySaveDataRequestBus::Handler::BusConnect(GetEntityId());
  924. }
  925. void SceneComponent::Activate()
  926. {
  927. GRAPH_CANVAS_PROFILE_FUNCTION();
  928. GraphCanvasPropertyComponent::Activate();
  929. // Need to register this before activating saved nodes. Otherwise data is not properly setup.
  930. const AZ::EntityId& entityId = GetEntityId();
  931. SceneRequestBus::Handler::BusConnect(entityId);
  932. SceneMimeDelegateRequestBus::Handler::BusConnect(entityId);
  933. SceneBookmarkActionBus::Handler::BusConnect(entityId);
  934. // Only want to activate the scene if we have something to activate
  935. // Otherwise elements may be repeatedly activated/registered to the scene.
  936. m_activateScene = !m_graphData.m_nodes.empty() || !m_graphData.m_bookmarkAnchors.empty();
  937. m_mimeDelegateSceneHelper.SetSceneId(entityId);
  938. m_gestureSceneHelper.SetSceneId(entityId);
  939. m_nudgingController.SetGraphId(entityId);
  940. m_mimeDelegateSceneHelper.Activate();
  941. m_gestureSceneHelper.Activate();
  942. }
  943. void SceneComponent::Deactivate()
  944. {
  945. GRAPH_CANVAS_PROFILE_FUNCTION();
  946. m_mimeDelegateSceneHelper.Deactivate();
  947. m_gestureSceneHelper.Deactivate();
  948. GraphCanvasPropertyComponent::Deactivate();
  949. SceneBookmarkActionBus::Handler::BusDisconnect();
  950. SceneMimeDelegateRequestBus::Handler::BusDisconnect();
  951. SceneRequestBus::Handler::BusDisconnect();
  952. AssetEditorSettingsNotificationBus::Handler::BusDisconnect();
  953. m_activeDelegates.clear();
  954. DeactivateItems(m_graphData.m_connections);
  955. DeactivateItems(m_graphData.m_nodes);
  956. DeactivateItems(m_graphData.m_bookmarkAnchors);
  957. DeactivateItems(AZStd::initializer_list<AZ::Entity*>{ AzToolsFramework::GetEntity(m_grid) });
  958. SceneMemberRequestBus::Event(m_grid, &SceneMemberRequests::ClearScene, GetEntityId());
  959. }
  960. void SceneComponent::OnSystemTick()
  961. {
  962. ProcessEnableDisableQueue();
  963. }
  964. void SceneComponent::OnEntityExists(const AZ::EntityId& /*entityId*/)
  965. {
  966. AZ::Entity* entity = GetEntity();
  967. // A less then ideal way of doing version control on the scenes
  968. BookmarkManagerComponent* bookmarkComponent = entity->FindComponent<BookmarkManagerComponent>();
  969. if (bookmarkComponent == nullptr)
  970. {
  971. entity->CreateComponent<BookmarkManagerComponent>();
  972. }
  973. AZ::EntityBus::Handler::BusDisconnect(GetEntityId());
  974. }
  975. void SceneComponent::WriteSaveData(EntitySaveDataContainer& saveDataContainer) const
  976. {
  977. GRAPH_CANVAS_PROFILE_FUNCTION();
  978. SceneComponentSaveData* saveData = saveDataContainer.FindCreateSaveData<SceneComponentSaveData>();
  979. saveData->ClearConstructData();
  980. for (AZ::Entity* currentEntity : m_graphData.m_nodes)
  981. {
  982. if (GraphUtils::IsComment(currentEntity->GetId()))
  983. {
  984. GraphCanvasConstructSaveData* constructSaveData = aznew GraphCanvasConstructSaveData();
  985. constructSaveData->m_constructType = ConstructType::CommentNode;
  986. EntitySaveDataRequestBus::Event(currentEntity->GetId(), &EntitySaveDataRequests::WriteSaveData, constructSaveData->m_saveDataContainer);
  987. saveData->m_constructs.push_back(constructSaveData);
  988. continue;
  989. }
  990. if (GraphUtils::IsNodeGroup(currentEntity->GetId()))
  991. {
  992. GraphCanvasConstructSaveData* constructSaveData = aznew GraphCanvasConstructSaveData();
  993. constructSaveData->m_constructType = ConstructType::NodeGroup;
  994. EntitySaveDataRequestBus::Event(currentEntity->GetId(), &EntitySaveDataRequests::WriteSaveData, constructSaveData->m_saveDataContainer);
  995. saveData->m_constructs.push_back(constructSaveData);
  996. continue;
  997. }
  998. }
  999. saveData->m_constructs.reserve(saveData->m_constructs.size() + m_graphData.m_bookmarkAnchors.size());
  1000. for (AZ::Entity* currentEntity : m_graphData.m_bookmarkAnchors)
  1001. {
  1002. GraphCanvasConstructSaveData* constructSaveData = aznew GraphCanvasConstructSaveData();
  1003. constructSaveData->m_constructType = ConstructType::BookmarkAnchor;
  1004. EntitySaveDataRequestBus::Event(currentEntity->GetId(), &EntitySaveDataRequests::WriteSaveData, constructSaveData->m_saveDataContainer);
  1005. saveData->m_constructs.push_back(constructSaveData);
  1006. }
  1007. saveData->m_viewParams = m_viewParams;
  1008. saveData->m_bookmarkCounter = m_bookmarkCounter;
  1009. }
  1010. void SceneComponent::ReadSaveData(const EntitySaveDataContainer& saveDataContainer)
  1011. {
  1012. GRAPH_CANVAS_PROFILE_FUNCTION();
  1013. if (const SceneComponentSaveData* saveData = saveDataContainer.FindSaveDataAs<SceneComponentSaveData>())
  1014. {
  1015. for (const GraphCanvasConstructSaveData* currentConstruct : saveData->m_constructs)
  1016. {
  1017. AZ::Entity* constructEntity = nullptr;
  1018. switch (currentConstruct->m_constructType)
  1019. {
  1020. case ConstructType::CommentNode:
  1021. GraphCanvasRequestBus::BroadcastResult(constructEntity, &GraphCanvasRequests::CreateCommentNode);
  1022. break;
  1023. case ConstructType::NodeGroup:
  1024. GraphCanvasRequestBus::BroadcastResult(constructEntity, &GraphCanvasRequests::CreateNodeGroup);
  1025. break;
  1026. case ConstructType::BookmarkAnchor:
  1027. GraphCanvasRequestBus::BroadcastResult(constructEntity, &GraphCanvasRequests::CreateBookmarkAnchor);
  1028. break;
  1029. default:
  1030. break;
  1031. }
  1032. if (constructEntity)
  1033. {
  1034. constructEntity->Init();
  1035. constructEntity->Activate();
  1036. EntitySaveDataRequestBus::Event(constructEntity->GetId(), &EntitySaveDataRequests::ReadSaveData, currentConstruct->m_saveDataContainer);
  1037. Add(constructEntity->GetId());
  1038. }
  1039. }
  1040. m_viewParams = saveData->m_viewParams;
  1041. m_bookmarkCounter = saveData->m_bookmarkCounter;
  1042. }
  1043. }
  1044. AZStd::any* SceneComponent::GetUserData()
  1045. {
  1046. return &m_graphData.m_userData;
  1047. }
  1048. const AZStd::any* SceneComponent::GetUserDataConst() const
  1049. {
  1050. return &m_graphData.m_userData;
  1051. }
  1052. void SceneComponent::SetEditorId(const EditorId& editorId)
  1053. {
  1054. if (m_editorId != editorId)
  1055. {
  1056. m_editorId = editorId;
  1057. m_mimeDelegateSceneHelper.SetEditorId(editorId);
  1058. m_gestureSceneHelper.SetEditorId(editorId);
  1059. OnSettingsChanged();
  1060. AssetEditorSettingsNotificationBus::Handler::BusConnect(m_editorId);
  1061. StyleManagerNotificationBus::Handler::BusConnect(m_editorId);
  1062. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnStylesChanged);
  1063. StyleNotificationBus::Event(m_grid, &StyleNotifications::OnStyleChanged);
  1064. }
  1065. }
  1066. EditorId SceneComponent::GetEditorId() const
  1067. {
  1068. return m_editorId;
  1069. }
  1070. AZ::EntityId SceneComponent::GetGrid() const
  1071. {
  1072. return m_grid;
  1073. }
  1074. GraphicsEffectId SceneComponent::CreatePulse(const AnimatedPulseConfiguration& pulseConfiguration)
  1075. {
  1076. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1077. AnimatedPulse* animatedPulse = aznew AnimatedPulse(pulseConfiguration);
  1078. ConfigureAndAddGraphicsEffect(animatedPulse);
  1079. return animatedPulse->GetEffectId();
  1080. }
  1081. GraphicsEffectId SceneComponent::CreatePulseAroundArea(const QRectF& area, int gridSteps, AnimatedPulseConfiguration& pulseConfiguration)
  1082. {
  1083. AZ::EntityId gridId = GetGrid();
  1084. AZ::Vector2 minorPitch(0, 0);
  1085. GridRequestBus::EventResult(minorPitch, gridId, &GridRequests::GetMinorPitch);
  1086. pulseConfiguration.m_controlPoints.reserve(4);
  1087. for (QPointF currentPoint : { area.topLeft(), area.topRight(), area.bottomRight(), area.bottomLeft()})
  1088. {
  1089. QPointF directionVector = currentPoint - area.center();
  1090. directionVector = QtVectorMath::Normalize(directionVector);
  1091. QPointF finalPoint(currentPoint.x() + directionVector.x() * minorPitch.GetX() * gridSteps, currentPoint.y() + directionVector.y() * minorPitch.GetY() * gridSteps);
  1092. pulseConfiguration.m_controlPoints.emplace_back(currentPoint, finalPoint);
  1093. }
  1094. return CreatePulse(pulseConfiguration);
  1095. }
  1096. GraphicsEffectId SceneComponent::CreatePulseAroundSceneMember(const AZ::EntityId& memberId, int gridSteps, AnimatedPulseConfiguration pulseConfiguration)
  1097. {
  1098. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1099. QGraphicsItem* graphicsItem = nullptr;
  1100. SceneMemberUIRequestBus::EventResult(graphicsItem, memberId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1101. if (graphicsItem)
  1102. {
  1103. QRectF target = graphicsItem->sceneBoundingRect();
  1104. return CreatePulseAroundArea(target, gridSteps, pulseConfiguration);
  1105. }
  1106. return AZ::EntityId();
  1107. }
  1108. GraphicsEffectId SceneComponent::CreateCircularPulse(const AZ::Vector2& point, float initialRadius, float finalRadius, AnimatedPulseConfiguration pulseConfiguration)
  1109. {
  1110. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1111. static const int k_circleSegemnts = 9;
  1112. pulseConfiguration.m_controlPoints.clear();
  1113. pulseConfiguration.m_controlPoints.reserve(k_circleSegemnts);
  1114. float step = AZ::Constants::TwoPi / static_cast<float>(k_circleSegemnts);
  1115. // Start it at some random offset just to hide the staticness of it.
  1116. float currentAngle = AZ::Constants::TwoPi * (static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX));
  1117. for (int i = 0; i < k_circleSegemnts; ++i)
  1118. {
  1119. QPointF outerPoint;
  1120. outerPoint.setX(point.GetX() + initialRadius * std::sin(currentAngle));
  1121. outerPoint.setY(point.GetY() + initialRadius * std::cos(currentAngle));
  1122. QPointF innerPoint;
  1123. innerPoint.setX(point.GetX() + finalRadius * std::sin(currentAngle));
  1124. innerPoint.setY(point.GetY() + finalRadius * std::cos(currentAngle));
  1125. currentAngle += step;
  1126. if (currentAngle > AZ::Constants::TwoPi)
  1127. {
  1128. currentAngle -= AZ::Constants::TwoPi;
  1129. }
  1130. pulseConfiguration.m_controlPoints.emplace_back(outerPoint, innerPoint);
  1131. }
  1132. return CreatePulse(pulseConfiguration);
  1133. }
  1134. GraphicsEffectId SceneComponent::CreateOccluder(const OccluderConfiguration& occluderConfiguration)
  1135. {
  1136. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1137. Occluder* occluder = aznew Occluder(occluderConfiguration);
  1138. ConfigureAndAddGraphicsEffect(occluder);
  1139. return occluder->GetEffectId();
  1140. }
  1141. GraphicsEffectId SceneComponent::CreateGlow(const FixedGlowOutlineConfiguration& configuration)
  1142. {
  1143. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1144. GlowOutlineGraphicsItem* outlineGraphicsItem = aznew GlowOutlineGraphicsItem(configuration);
  1145. ConfigureAndAddGraphicsEffect(outlineGraphicsItem);
  1146. return outlineGraphicsItem->GetEffectId();
  1147. }
  1148. GraphicsEffectId SceneComponent::CreateGlowOnSceneMember(const SceneMemberGlowOutlineConfiguration& configuration)
  1149. {
  1150. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1151. QGraphicsItem* graphicsItem = nullptr;
  1152. VisualRequestBus::EventResult(graphicsItem, configuration.m_sceneMember, &VisualRequests::AsGraphicsItem);
  1153. if (m_hiddenElements.count(graphicsItem) == 0)
  1154. {
  1155. GlowOutlineGraphicsItem* outlineGraphicsItem = aznew GlowOutlineGraphicsItem(configuration);
  1156. ConfigureAndAddGraphicsEffect(outlineGraphicsItem);
  1157. return outlineGraphicsItem->GetEffectId();
  1158. }
  1159. else
  1160. {
  1161. return GraphicsEffectId();
  1162. }
  1163. }
  1164. GraphicsEffectId SceneComponent::CreateParticle(const ParticleConfiguration& configuration)
  1165. {
  1166. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1167. if constexpr (k_particleLimit == 0)
  1168. {
  1169. return GraphicsEffectId();
  1170. }
  1171. ParticleGraphicsItem* particleGraphicsItem = aznew ParticleGraphicsItem(configuration);
  1172. ConfigureAndAddGraphicsEffect(particleGraphicsItem);
  1173. m_activeParticles.emplace_back(particleGraphicsItem->GetEffectId());
  1174. if (m_activeParticles.size() >= k_particleLimit)
  1175. {
  1176. CancelGraphicsEffect(m_activeParticles.front());
  1177. }
  1178. return particleGraphicsItem->GetEffectId();
  1179. }
  1180. AZStd::vector< GraphicsEffectId > SceneComponent::ExplodeSceneMember(const AZ::EntityId& memberId, float fillPercent)
  1181. {
  1182. AZStd::vector< GraphicsEffectId > effectIds;
  1183. if (GraphUtils::IsNode(memberId) || GraphUtils::IsNodeGroup(memberId))
  1184. {
  1185. const Styling::StyleHelper* styleHelper = nullptr;
  1186. QColor drawColor;
  1187. if (GraphUtils::IsCollapsedNodeGroup(memberId))
  1188. {
  1189. AZ::EntityId sourceGroupId;
  1190. CollapsedNodeGroupRequestBus::EventResult(sourceGroupId, memberId, &CollapsedNodeGroupRequests::GetSourceGroup);
  1191. AZ::Color azColor;
  1192. NodeGroupRequestBus::EventResult(azColor, sourceGroupId, &NodeGroupRequests::GetGroupColor);
  1193. drawColor = ConversionUtils::AZToQColor(azColor);
  1194. }
  1195. else if (GraphUtils::IsNode(memberId))
  1196. {
  1197. PaletteIconConfiguration iconConfiguration;
  1198. NodeTitleRequestBus::Event(memberId, &NodeTitleRequests::ConfigureIconConfiguration, iconConfiguration);
  1199. StyleManagerRequestBus::EventResult(styleHelper, m_editorId, &StyleManagerRequests::FindPaletteIconStyleHelper, iconConfiguration);
  1200. }
  1201. else
  1202. {
  1203. AZ::Color azColor;
  1204. NodeGroupRequestBus::EventResult(azColor, memberId, &NodeGroupRequests::GetGroupColor);
  1205. drawColor = ConversionUtils::AZToQColor(azColor);
  1206. }
  1207. QGraphicsItem* graphicsItem = nullptr;
  1208. SceneMemberUIRequestBus::EventResult(graphicsItem, memberId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1209. if (graphicsItem)
  1210. {
  1211. QRectF boundingRect = graphicsItem->sceneBoundingRect();
  1212. AZ::Vector2 minorPitch;
  1213. GridRequestBus::EventResult(minorPitch, GetGrid(), &GridRequests::GetMinorPitch);
  1214. AZ::Vector2 boxSize = minorPitch;
  1215. AZ::Vector2 impulseVector = minorPitch;
  1216. ParticleConfiguration baseConfiguration;
  1217. baseConfiguration.m_boundingArea = QRectF(0,0, boxSize.GetX(), boxSize.GetY());
  1218. baseConfiguration.m_hasGravity = true;
  1219. baseConfiguration.m_alphaFade = true;
  1220. baseConfiguration.m_alphaStart = 1.0f;
  1221. baseConfiguration.m_alphaEnd = 0.0f;
  1222. baseConfiguration.m_styleHelper = styleHelper;
  1223. baseConfiguration.m_color = drawColor;
  1224. baseConfiguration.m_zValue = aznumeric_cast<int>(graphicsItem->zValue());
  1225. boundingRect.adjust(minorPitch.GetX() * 0.5f, minorPitch.GetY() * 0.5f, -minorPitch.GetX() * 0.5f, -minorPitch.GetY() * 0.5f);
  1226. int yPos = aznumeric_cast<int>(boundingRect.top());
  1227. int xPos = aznumeric_cast<int>(boundingRect.left());
  1228. while (yPos < boundingRect.bottom())
  1229. {
  1230. while (xPos < boundingRect.right())
  1231. {
  1232. float skipChance = static_cast<float>(rand()) / static_cast<float>(RAND_MAX);
  1233. if (skipChance <= fillPercent)
  1234. {
  1235. baseConfiguration.m_boundingArea.moveTopLeft(QPointF(xPos, yPos));
  1236. double impulseVariance = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
  1237. double directionSpray = ((boundingRect.center().x() - xPos)/boundingRect.width()) * 2.0;
  1238. double xImpulse = impulseVector.GetX() * 10.0 * -directionSpray + impulseVector.GetX() * 6.0 * impulseVariance;
  1239. double yImpulse = -impulseVector.GetY() * 4.0 - impulseVector.GetY() * 2.0 * impulseVariance;
  1240. baseConfiguration.m_initialImpulse = QPointF(xImpulse, yImpulse);
  1241. baseConfiguration.m_lifespan = AZStd::chrono::milliseconds(400 + rand() % 125);
  1242. baseConfiguration.m_fadeTime = baseConfiguration.m_lifespan;
  1243. effectIds.emplace_back(CreateParticle(baseConfiguration));
  1244. }
  1245. xPos += aznumeric_cast<int>(minorPitch.GetX());
  1246. }
  1247. yPos += aznumeric_cast<int>(minorPitch.GetY());
  1248. xPos = aznumeric_cast<int>(boundingRect.left());
  1249. }
  1250. }
  1251. }
  1252. return effectIds;
  1253. }
  1254. void SceneComponent::CancelGraphicsEffect(const GraphicsEffectId& effectId)
  1255. {
  1256. QGraphicsItem* graphicsItem = nullptr;
  1257. GraphicsEffectRequestBus::EventResult(graphicsItem, effectId, &GraphicsEffectRequests::AsQGraphicsItem);
  1258. DestroyGraphicsItem(effectId, graphicsItem);
  1259. }
  1260. bool SceneComponent::AddNode(const AZ::EntityId& nodeId, const AZ::Vector2& position, bool isPaste)
  1261. {
  1262. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1263. AZ::Entity* nodeEntity(AzToolsFramework::GetEntity(nodeId));
  1264. AZ_Assert(nodeEntity, "Node (ID: %s) Entity not found!", nodeId.ToString().data());
  1265. AZ_Assert(nodeEntity->GetState() == AZ::Entity::State::Active, "Only active node entities can be added to a scene");
  1266. QGraphicsItem* item = nullptr;
  1267. SceneMemberUIRequestBus::EventResult(item, nodeId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1268. AZ_Assert(item && !item->parentItem(), "Nodes must have a \"root\", unparented visual/QGraphicsItem");
  1269. auto foundIt = AZStd::find_if(m_graphData.m_nodes.begin(), m_graphData.m_nodes.end(), [&nodeEntity](const AZ::Entity* node) { return node->GetId() == nodeEntity->GetId(); });
  1270. if (foundIt == m_graphData.m_nodes.end())
  1271. {
  1272. m_graphData.m_nodes.emplace(nodeEntity);
  1273. AddSceneMember(nodeId, true, position);
  1274. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnNodeAdded, nodeId, isPaste);
  1275. m_mimeDelegateSceneHelper.SignalNodeCreated(nodeId);
  1276. return true;
  1277. }
  1278. return false;
  1279. }
  1280. void SceneComponent::AddNodes(const AZStd::vector<AZ::EntityId>& nodeIds)
  1281. {
  1282. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1283. for (const auto& nodeId : nodeIds)
  1284. {
  1285. AZ::Vector2 position;
  1286. GeometryRequestBus::EventResult(position, nodeId, &GeometryRequests::GetPosition);
  1287. AddNode(nodeId, position, false);
  1288. }
  1289. }
  1290. bool SceneComponent::RemoveNode(const AZ::EntityId& nodeId)
  1291. {
  1292. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1293. auto foundIt = AZStd::find_if(m_graphData.m_nodes.begin(), m_graphData.m_nodes.end(), [&nodeId](const AZ::Entity* node) { return node->GetId() == nodeId; });
  1294. if (foundIt != m_graphData.m_nodes.end())
  1295. {
  1296. VisualNotificationBus::MultiHandler::BusDisconnect(nodeId);
  1297. GeometryNotificationBus::MultiHandler::BusDisconnect(nodeId);
  1298. m_graphData.m_nodes.erase(foundIt);
  1299. SceneMemberNotificationBus::Event(nodeId, &SceneMemberNotifications::PreOnRemovedFromScene, GetEntityId());
  1300. QGraphicsItem* item = nullptr;
  1301. SceneMemberUIRequestBus::EventResult(item, nodeId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1302. RemoveItemFromScene(item);
  1303. UnregisterSelectionItem(nodeId);
  1304. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnNodeRemoved, nodeId);
  1305. SceneMemberRequestBus::Event(nodeId, &SceneMemberRequests::ClearScene, GetEntityId());
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. AZStd::vector<AZ::EntityId> SceneComponent::GetNodes() const
  1311. {
  1312. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1313. AZStd::vector<AZ::EntityId> result;
  1314. for (const auto& nodeRef : m_graphData.m_nodes)
  1315. {
  1316. result.push_back(nodeRef->GetId());
  1317. }
  1318. return result;
  1319. }
  1320. AZStd::vector<AZ::EntityId> SceneComponent::GetSelectedNodes() const
  1321. {
  1322. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1323. AZStd::vector<AZ::EntityId> result;
  1324. if (m_graphicsSceneUi)
  1325. {
  1326. const QList<QGraphicsItem*> selected(m_graphicsSceneUi->selectedItems());
  1327. result.reserve(selected.size());
  1328. for (QGraphicsItem* item : selected)
  1329. {
  1330. auto entry = m_itemLookup.find(item);
  1331. if (entry != m_itemLookup.end())
  1332. {
  1333. AZ::Entity* entity = nullptr;
  1334. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entry->second);
  1335. if (m_graphData.m_nodes.count(entity) > 0)
  1336. {
  1337. result.push_back(entity->GetId());
  1338. }
  1339. }
  1340. }
  1341. }
  1342. return result;
  1343. }
  1344. void SceneComponent::DeleteNodeAndStitchConnections(const AZ::EntityId& node)
  1345. {
  1346. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1347. if (node.IsValid())
  1348. {
  1349. ScopedGraphUndoBatch undoBatch(GetEntityId());
  1350. float explosionDensity = 0.6f;
  1351. if (GraphUtils::IsNodeGroup(node))
  1352. {
  1353. explosionDensity = 0.3f;
  1354. }
  1355. ExplodeSceneMember(node, explosionDensity);
  1356. GraphUtils::DetachNodeAndStitchConnections(node);
  1357. Delete({ node });
  1358. }
  1359. }
  1360. AZ::EntityId SceneComponent::CreateConnectionBetween(const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint)
  1361. {
  1362. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1363. if (!sourceEndpoint.IsValid() || !targetEndpoint.IsValid())
  1364. {
  1365. return AZ::EntityId();
  1366. }
  1367. AZ::EntityId connectionId;
  1368. bool isValidConnection = false;
  1369. SlotRequestBus::EventResult(isValidConnection, sourceEndpoint.GetSlotId(), &SlotRequests::CanCreateConnectionTo, targetEndpoint);
  1370. if (isValidConnection)
  1371. {
  1372. SlotRequestBus::EventResult(connectionId, sourceEndpoint.GetSlotId(), &SlotRequests::CreateConnectionWithEndpoint, targetEndpoint);
  1373. }
  1374. return connectionId;
  1375. }
  1376. bool SceneComponent::AddConnection(const AZ::EntityId& connectionId)
  1377. {
  1378. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1379. AZ_Assert(connectionId.IsValid(), "Connection ID %s is not valid!", connectionId.ToString().data());
  1380. AZ::Entity* connectionEntity(AzToolsFramework::GetEntity(connectionId));
  1381. auto connection = connectionEntity ? AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(connectionEntity) : nullptr;
  1382. AZ_Warning("Graph Canvas", connection->GetEntity()->GetState() == AZ::Entity::State::Active, "Only active connection entities can be added to a scene");
  1383. AZ_Warning("Graph Canvas", connection, "Couldn't find the connection's component (ID: %s)!", connectionId.ToString().data());
  1384. if (connection)
  1385. {
  1386. auto foundIt = AZStd::find_if(m_graphData.m_connections.begin(), m_graphData.m_connections.end(), [&connection](const AZ::Entity* connectionEntity) { return connectionEntity->GetId() == connection->GetEntityId(); });
  1387. if (foundIt == m_graphData.m_connections.end())
  1388. {
  1389. AddSceneMember(connectionId);
  1390. m_graphData.m_connections.emplace(connection->GetEntity());
  1391. Endpoint sourceEndpoint;
  1392. ConnectionRequestBus::EventResult(sourceEndpoint, connectionId, &ConnectionRequests::GetSourceEndpoint);
  1393. Endpoint targetEndpoint;
  1394. ConnectionRequestBus::EventResult(targetEndpoint, connectionId, &ConnectionRequests::GetTargetEndpoint);
  1395. m_graphData.m_endpointMap.emplace(sourceEndpoint, targetEndpoint);
  1396. m_graphData.m_endpointMap.emplace(targetEndpoint, sourceEndpoint);
  1397. SlotRequestBus::Event(sourceEndpoint.GetSlotId(), &SlotRequests::AddConnectionId, connectionId, targetEndpoint);
  1398. SlotRequestBus::Event(targetEndpoint.GetSlotId(), &SlotRequests::AddConnectionId, connectionId, sourceEndpoint);
  1399. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnConnectionAdded, connectionId);
  1400. return true;
  1401. }
  1402. }
  1403. return false;
  1404. }
  1405. void SceneComponent::AddConnections(const AZStd::vector<AZ::EntityId>& connectionIds)
  1406. {
  1407. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1408. for (const auto& connectionId : connectionIds)
  1409. {
  1410. AddConnection(connectionId);
  1411. }
  1412. }
  1413. bool SceneComponent::RemoveConnection(const AZ::EntityId& connectionId)
  1414. {
  1415. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1416. AZ_Assert(connectionId.IsValid(), "Connection ID %s is not valid!", connectionId.ToString().data());
  1417. auto foundIt = AZStd::find_if(m_graphData.m_connections.begin(), m_graphData.m_connections.end(), [&connectionId](const AZ::Entity* connection) { return connection->GetId() == connectionId; });
  1418. if (foundIt != m_graphData.m_connections.end())
  1419. {
  1420. VisualNotificationBus::MultiHandler::BusDisconnect(connectionId);
  1421. GeometryNotificationBus::MultiHandler::BusDisconnect(connectionId);
  1422. Endpoint sourceEndpoint;
  1423. ConnectionRequestBus::EventResult(sourceEndpoint, connectionId, &ConnectionRequests::GetSourceEndpoint);
  1424. Endpoint targetEndpoint;
  1425. ConnectionRequestBus::EventResult(targetEndpoint, connectionId, &ConnectionRequests::GetTargetEndpoint);
  1426. m_graphData.m_endpointMap.erase(sourceEndpoint);
  1427. m_graphData.m_endpointMap.erase(targetEndpoint);
  1428. m_graphData.m_connections.erase(foundIt);
  1429. QGraphicsItem* item{};
  1430. SceneMemberUIRequestBus::EventResult(item, connectionId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1431. AZ_Assert(item, "Connections must have a visual/QGraphicsItem");
  1432. RemoveItemFromScene(item);
  1433. UnregisterSelectionItem(connectionId);
  1434. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnConnectionRemoved, connectionId);
  1435. SlotRequestBus::Event(targetEndpoint.GetSlotId(), &SlotRequests::RemoveConnectionId, connectionId, sourceEndpoint);
  1436. SlotRequestBus::Event(sourceEndpoint.GetSlotId(), &SlotRequests::RemoveConnectionId, connectionId, targetEndpoint);
  1437. return true;
  1438. }
  1439. return false;
  1440. }
  1441. AZStd::vector<AZ::EntityId> SceneComponent::GetConnections() const
  1442. {
  1443. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1444. AZStd::vector<AZ::EntityId> result;
  1445. for (const auto& connection : m_graphData.m_connections)
  1446. {
  1447. result.push_back(connection->GetId());
  1448. }
  1449. return result;
  1450. }
  1451. AZStd::vector<AZ::EntityId> SceneComponent::GetSelectedConnections() const
  1452. {
  1453. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1454. AZStd::vector<AZ::EntityId> result;
  1455. if (m_graphicsSceneUi)
  1456. {
  1457. const QList<QGraphicsItem*> selected(m_graphicsSceneUi->selectedItems());
  1458. result.reserve(selected.size());
  1459. for (QGraphicsItem* item : selected)
  1460. {
  1461. auto entry = m_itemLookup.find(item);
  1462. if (entry != m_itemLookup.end())
  1463. {
  1464. AZ::Entity* entity{};
  1465. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entry->second);
  1466. if (entity && AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(entity))
  1467. {
  1468. result.push_back(entity->GetId());
  1469. }
  1470. }
  1471. }
  1472. }
  1473. return result;
  1474. }
  1475. AZStd::vector<AZ::EntityId> SceneComponent::GetConnectionsForEndpoint(const Endpoint& firstEndpoint) const
  1476. {
  1477. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1478. AZStd::vector<AZ::EntityId> result;
  1479. for (const auto& connection : m_graphData.m_connections)
  1480. {
  1481. Endpoint sourceEndpoint;
  1482. ConnectionRequestBus::EventResult(sourceEndpoint, connection->GetId(), &ConnectionRequests::GetSourceEndpoint);
  1483. Endpoint targetEndpoint;
  1484. ConnectionRequestBus::EventResult(targetEndpoint, connection->GetId(), &ConnectionRequests::GetTargetEndpoint);
  1485. if (sourceEndpoint == firstEndpoint || targetEndpoint == firstEndpoint)
  1486. {
  1487. result.push_back(connection->GetId());
  1488. }
  1489. }
  1490. return result;
  1491. }
  1492. bool SceneComponent::IsEndpointConnected(const Endpoint& endpoint) const
  1493. {
  1494. return m_graphData.m_endpointMap.count(endpoint) > 0;
  1495. }
  1496. AZStd::vector<Endpoint> SceneComponent::GetConnectedEndpoints(const Endpoint& firstEndpoint) const
  1497. {
  1498. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1499. AZStd::vector<Endpoint> connectedEndpoints;
  1500. auto otherEndpointsRange = m_graphData.m_endpointMap.equal_range(firstEndpoint);
  1501. for (auto otherIt = otherEndpointsRange.first; otherIt != otherEndpointsRange.second; ++otherIt)
  1502. {
  1503. connectedEndpoints.push_back(otherIt->second);
  1504. }
  1505. return connectedEndpoints;
  1506. }
  1507. bool SceneComponent::CreateConnection(const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint)
  1508. {
  1509. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1510. AZ::Entity* foundEntity = nullptr;
  1511. if (FindConnection(foundEntity, sourceEndpoint, targetEndpoint))
  1512. {
  1513. AZ_Warning("Graph Canvas", false, "Attempting to create duplicate connection between source endpoint (%s, %s) and target endpoint(%s, %s)",
  1514. sourceEndpoint.GetNodeId().ToString().data(), sourceEndpoint.GetSlotId().ToString().data(),
  1515. targetEndpoint.GetNodeId().ToString().data(), targetEndpoint.GetSlotId().ToString().data());
  1516. return false;
  1517. }
  1518. // Hunt through our nodes for both the source and target endpoint at the same time.
  1519. AZStd::pair<bool, bool> findResult(false, false);
  1520. AZStd::find_if(m_graphData.m_nodes.begin(), m_graphData.m_nodes.end(), [&findResult, &sourceEndpoint, &targetEndpoint](const AZ::Entity* node)
  1521. {
  1522. findResult.first = findResult.first || node->GetId() == sourceEndpoint.GetNodeId();
  1523. findResult.second = findResult.second || node->GetId() == targetEndpoint.GetNodeId();
  1524. return findResult.first && findResult.second;
  1525. }
  1526. );
  1527. if (!findResult.first)
  1528. {
  1529. AZ_Error("Scene", false, "The source node with id %s is not in this scene, a connection cannot be made", sourceEndpoint.GetNodeId().ToString().data());
  1530. return false;
  1531. }
  1532. else if (!findResult.second)
  1533. {
  1534. AZ_Error("Scene", false, "The target node with id %s is not in this scene, a connection cannot be made", targetEndpoint.GetNodeId().ToString().data());
  1535. return false;
  1536. }
  1537. AZ::EntityId connectionEntity;
  1538. SlotRequestBus::EventResult(connectionEntity, sourceEndpoint.GetSlotId(), &SlotRequests::CreateConnectionWithEndpoint, targetEndpoint);
  1539. return true;
  1540. }
  1541. bool SceneComponent::DisplayConnection(const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint)
  1542. {
  1543. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1544. AZ::Entity* foundEntity = nullptr;
  1545. if (FindConnection(foundEntity, sourceEndpoint, targetEndpoint))
  1546. {
  1547. AZ_Warning("Graph Canvas", false, "Attempting to create duplicate connection between source endpoint (%s, %s) and target endpoint(%s, %s)",
  1548. sourceEndpoint.GetNodeId().ToString().data(), sourceEndpoint.GetSlotId().ToString().data(),
  1549. targetEndpoint.GetNodeId().ToString().data(), targetEndpoint.GetSlotId().ToString().data());
  1550. return false;
  1551. }
  1552. // Hunt through our nodes for both the source and target endpoint at the same time.
  1553. AZStd::pair<bool, bool> findResult(false, false);
  1554. AZStd::find_if(m_graphData.m_nodes.begin(), m_graphData.m_nodes.end(), [&findResult, &sourceEndpoint, &targetEndpoint](const AZ::Entity* node)
  1555. {
  1556. findResult.first = findResult.first || node->GetId() == sourceEndpoint.GetNodeId();
  1557. findResult.second = findResult.second || node->GetId() == targetEndpoint.GetNodeId();
  1558. return findResult.first && findResult.second;
  1559. }
  1560. );
  1561. if (!findResult.first)
  1562. {
  1563. AZ_Error("Scene", false, "The source node with id %s is not in this scene, a connection cannot be made", sourceEndpoint.GetNodeId().ToString().data());
  1564. return false;
  1565. }
  1566. else if (!findResult.second)
  1567. {
  1568. AZ_Error("Scene", false, "The target node with id %s is not in this scene, a connection cannot be made", targetEndpoint.GetNodeId().ToString().data());
  1569. return false;
  1570. }
  1571. AZ::EntityId connectionEntity;
  1572. SlotRequestBus::EventResult(connectionEntity, sourceEndpoint.GetSlotId(), &SlotRequests::DisplayConnectionWithEndpoint, targetEndpoint);
  1573. return true;
  1574. }
  1575. bool SceneComponent::Disconnect(const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint)
  1576. {
  1577. AZ::Entity* connectionEntity = nullptr;
  1578. if (FindConnection(connectionEntity, sourceEndpoint, targetEndpoint) && RemoveConnection(connectionEntity->GetId()))
  1579. {
  1580. delete connectionEntity;
  1581. return true;
  1582. }
  1583. return false;
  1584. }
  1585. bool SceneComponent::DisconnectById(const AZ::EntityId& connectionId)
  1586. {
  1587. if (RemoveConnection(connectionId))
  1588. {
  1589. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, connectionId);
  1590. return true;
  1591. }
  1592. return false;
  1593. }
  1594. bool SceneComponent::FindConnection(AZ::Entity*& connectionEntity, const Endpoint& sourceEndpoint, const Endpoint& targetEndpoint) const
  1595. {
  1596. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1597. AZ::Entity* foundEntity = nullptr;
  1598. AZStd::vector< ConnectionId > connectionIds;
  1599. SlotRequestBus::EventResult(connectionIds, sourceEndpoint.GetSlotId(), &SlotRequests::GetConnections);
  1600. for (const ConnectionId& connectionId : connectionIds)
  1601. {
  1602. Endpoint testTargetEndpoint;
  1603. ConnectionRequestBus::EventResult(testTargetEndpoint, connectionId, &ConnectionRequests::GetTargetEndpoint);
  1604. if (targetEndpoint == testTargetEndpoint)
  1605. {
  1606. AZ::ComponentApplicationBus::BroadcastResult(foundEntity, &AZ::ComponentApplicationRequests::FindEntity, connectionId);
  1607. break;
  1608. }
  1609. }
  1610. if (foundEntity)
  1611. {
  1612. connectionEntity = foundEntity;
  1613. return true;
  1614. }
  1615. return false;
  1616. }
  1617. bool SceneComponent::AddBookmarkAnchor(const AZ::EntityId& bookmarkAnchorId, const AZ::Vector2& position)
  1618. {
  1619. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1620. AZ::Entity* anchorEntity(AzToolsFramework::GetEntity(bookmarkAnchorId));
  1621. AZ_Assert(anchorEntity, "BookmarkAnchor (ID: %s) Entity not found!", bookmarkAnchorId.ToString().data());
  1622. AZ_Assert(anchorEntity->GetState() == AZ::Entity::State::Active, "Only active node entities can be added to a scene");
  1623. QGraphicsItem* item = nullptr;
  1624. SceneMemberUIRequestBus::EventResult(item, bookmarkAnchorId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1625. AZ_Assert(item && !item->parentItem(), "BookmarkAnchors must have a \"root\", unparented visual/QGraphicsItem");
  1626. auto foundIt = AZStd::find_if(m_graphData.m_bookmarkAnchors.begin(), m_graphData.m_bookmarkAnchors.end(), [&anchorEntity](const AZ::Entity* entity) { return entity->GetId() == anchorEntity->GetId(); });
  1627. if (foundIt == m_graphData.m_bookmarkAnchors.end())
  1628. {
  1629. m_graphData.m_bookmarkAnchors.emplace(anchorEntity);
  1630. AddSceneMember(bookmarkAnchorId, true, position);
  1631. return true;
  1632. }
  1633. return false;
  1634. }
  1635. bool SceneComponent::RemoveBookmarkAnchor(const AZ::EntityId& bookmarkAnchorId)
  1636. {
  1637. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1638. auto foundIt = AZStd::find_if(m_graphData.m_bookmarkAnchors.begin(), m_graphData.m_bookmarkAnchors.end(), [&bookmarkAnchorId](const AZ::Entity* anchorEntity) { return anchorEntity->GetId() == bookmarkAnchorId; });
  1639. if (foundIt != m_graphData.m_bookmarkAnchors.end())
  1640. {
  1641. VisualNotificationBus::MultiHandler::BusDisconnect(bookmarkAnchorId);
  1642. GeometryNotificationBus::MultiHandler::BusDisconnect(bookmarkAnchorId);
  1643. m_graphData.m_bookmarkAnchors.erase(foundIt);
  1644. QGraphicsItem* item = nullptr;
  1645. SceneMemberUIRequestBus::EventResult(item, bookmarkAnchorId, &SceneMemberUIRequests::GetRootGraphicsItem);
  1646. RemoveItemFromScene(item);
  1647. UnregisterSelectionItem(bookmarkAnchorId);
  1648. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSceneMemberRemoved, bookmarkAnchorId);
  1649. SceneMemberRequestBus::Event(bookmarkAnchorId, &SceneMemberRequests::ClearScene, GetEntityId());
  1650. return true;
  1651. }
  1652. return false;
  1653. }
  1654. bool SceneComponent::Add(const AZ::EntityId& entityId, bool isPaste)
  1655. {
  1656. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1657. AZ::Entity* actual = nullptr;
  1658. AZ::ComponentApplicationBus::BroadcastResult(actual, &AZ::ComponentApplicationRequests::FindEntity, entityId);
  1659. if (!actual)
  1660. {
  1661. return false;
  1662. }
  1663. if (AZ::EntityUtils::FindFirstDerivedComponent<NodeComponent>(actual))
  1664. {
  1665. AZ::Vector2 position;
  1666. GeometryRequestBus::EventResult(position, entityId, &GeometryRequests::GetPosition);
  1667. return AddNode(entityId, position, isPaste);
  1668. }
  1669. else if (AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(actual))
  1670. {
  1671. return AddConnection(entityId);
  1672. }
  1673. else if (AZ::EntityUtils::FindFirstDerivedComponent<BookmarkAnchorComponent>(actual))
  1674. {
  1675. AZ::Vector2 position;
  1676. GeometryRequestBus::EventResult(position, entityId, &GeometryRequests::GetPosition);
  1677. return AddBookmarkAnchor(entityId, position);
  1678. }
  1679. else
  1680. {
  1681. AZ_Error("Scene", false, "The entity does not appear to be a valid scene membership candidate (ID: %s)", entityId.ToString().data());
  1682. }
  1683. return false;
  1684. }
  1685. bool SceneComponent::Remove(const AZ::EntityId& entityId)
  1686. {
  1687. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1688. AZ::Entity* actual = nullptr;
  1689. AZ::ComponentApplicationBus::BroadcastResult(actual, &AZ::ComponentApplicationRequests::FindEntity, entityId);
  1690. if (!actual)
  1691. {
  1692. return false;
  1693. }
  1694. if (m_pressedEntity == entityId)
  1695. {
  1696. VisualNotificationBus::Event(m_pressedEntity, &VisualNotifications::OnMouseRelease, m_pressedEntity, nullptr);
  1697. }
  1698. if (AZ::EntityUtils::FindFirstDerivedComponent<NodeComponent>(actual))
  1699. {
  1700. return RemoveNode(entityId);
  1701. }
  1702. else if (AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(actual))
  1703. {
  1704. return RemoveConnection(entityId);
  1705. }
  1706. else if (AZ::EntityUtils::FindFirstDerivedComponent<BookmarkAnchorComponent>(actual))
  1707. {
  1708. return RemoveBookmarkAnchor(entityId);
  1709. }
  1710. else
  1711. {
  1712. AZ_Error("Scene", false, "The entity does not appear to be a valid scene membership candidate (ID: %s)", entityId.ToString().data());
  1713. }
  1714. return false;
  1715. }
  1716. bool SceneComponent::Show(const AZ::EntityId& graphMember)
  1717. {
  1718. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1719. if (m_graphicsSceneUi)
  1720. {
  1721. QGraphicsItem* graphicsItem = nullptr;
  1722. SceneMemberUIRequestBus::EventResult(graphicsItem, graphMember, &SceneMemberUIRequests::GetRootGraphicsItem);
  1723. if (graphicsItem)
  1724. {
  1725. auto hiddenIter = m_hiddenElements.find(graphicsItem);
  1726. bool isWrapped = false;
  1727. NodeRequestBus::EventResult(isWrapped, graphMember, &NodeRequests::IsWrapped);
  1728. if (!isWrapped)
  1729. {
  1730. if (hiddenIter != m_hiddenElements.end())
  1731. {
  1732. if (GeometryRequestBus::FindFirstHandler(graphMember) != nullptr)
  1733. {
  1734. AZ::Vector2 position(0, 0);
  1735. GeometryRequestBus::EventResult(position, graphMember, &GeometryRequests::GetPosition);
  1736. graphicsItem->setPos(ConversionUtils::AZToQPoint(position));
  1737. }
  1738. graphicsItem->show();
  1739. SceneMemberNotificationBus::Event(graphMember, &SceneMemberNotifications::OnSceneMemberShown);
  1740. m_hiddenElements.erase(hiddenIter);
  1741. return true;
  1742. }
  1743. }
  1744. else
  1745. {
  1746. if (hiddenIter != m_hiddenElements.end())
  1747. {
  1748. m_hiddenElements.erase(hiddenIter);
  1749. }
  1750. graphicsItem->show();
  1751. return true;
  1752. }
  1753. }
  1754. }
  1755. return false;
  1756. }
  1757. bool SceneComponent::Hide(const AZ::EntityId& graphMember)
  1758. {
  1759. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1760. if (m_graphicsSceneUi)
  1761. {
  1762. QGraphicsItem* graphicsItem = nullptr;
  1763. SceneMemberUIRequestBus::EventResult(graphicsItem, graphMember, &SceneMemberUIRequests::GetRootGraphicsItem);
  1764. if (graphicsItem)
  1765. {
  1766. graphicsItem->hide();
  1767. auto insertResult = m_hiddenElements.insert(graphicsItem);
  1768. if (insertResult.second)
  1769. {
  1770. SceneMemberNotificationBus::Event(graphMember, &SceneMemberNotifications::OnSceneMemberHidden);
  1771. }
  1772. return insertResult.second;
  1773. }
  1774. }
  1775. return false;
  1776. }
  1777. bool SceneComponent::IsHidden(const AZ::EntityId& graphMember) const
  1778. {
  1779. QGraphicsItem* graphicsItem = nullptr;
  1780. SceneMemberUIRequestBus::EventResult(graphicsItem, graphMember, &SceneMemberUIRequests::GetRootGraphicsItem);
  1781. return m_hiddenElements.find(graphicsItem) != m_hiddenElements.end();
  1782. }
  1783. bool SceneComponent::Enable(const NodeId& nodeId)
  1784. {
  1785. if (!AZ::SystemTickBus::Handler::BusIsConnected())
  1786. {
  1787. AZ::SystemTickBus::Handler::BusConnect();
  1788. }
  1789. m_queuedDisable.erase(nodeId);
  1790. auto insertResult = m_queuedEnable.insert(nodeId);
  1791. return insertResult.second;
  1792. }
  1793. void SceneComponent::EnableVisualState(const NodeId& nodeId)
  1794. {
  1795. if (!AZ::SystemTickBus::Handler::BusIsConnected())
  1796. {
  1797. AZ::SystemTickBus::Handler::BusConnect();
  1798. }
  1799. m_queuedVisualDisable.erase(nodeId);
  1800. m_queuedVisualEnable.insert(nodeId);
  1801. }
  1802. void SceneComponent::EnableSelection()
  1803. {
  1804. AZStd::vector< NodeId > selectedNodes = GetSelectedNodes();
  1805. for (NodeId nodeId : selectedNodes)
  1806. {
  1807. Enable(nodeId);
  1808. }
  1809. }
  1810. bool SceneComponent::Disable(const NodeId& nodeId)
  1811. {
  1812. if (!AZ::SystemTickBus::Handler::BusIsConnected())
  1813. {
  1814. AZ::SystemTickBus::Handler::BusConnect();
  1815. }
  1816. m_queuedEnable.erase(nodeId);
  1817. auto insertResult = m_queuedDisable.insert(nodeId);
  1818. return insertResult.second;
  1819. }
  1820. void SceneComponent::DisableVisualState(const NodeId& nodeId)
  1821. {
  1822. if (!AZ::SystemTickBus::Handler::BusIsConnected())
  1823. {
  1824. AZ::SystemTickBus::Handler::BusConnect();
  1825. }
  1826. m_queuedVisualEnable.erase(nodeId);
  1827. m_queuedVisualDisable.insert(nodeId);
  1828. }
  1829. void SceneComponent::DisableSelection()
  1830. {
  1831. AZStd::vector< NodeId > selectedNodes = GetSelectedNodes();
  1832. for (NodeId nodeId : selectedNodes)
  1833. {
  1834. // Temporarily disable collapsed node groups until we figure out how disabled groups should work.
  1835. //
  1836. // Node groups can still be partially disabled if they're connections are disabled, but you won't be able
  1837. // to disable them directly.
  1838. if (!GraphUtils::IsCollapsedNodeGroup(nodeId))
  1839. {
  1840. Disable(nodeId);
  1841. }
  1842. }
  1843. }
  1844. void SceneComponent::ProcessEnableDisableQueue()
  1845. {
  1846. if (!m_queuedDisable.empty())
  1847. {
  1848. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::DisableNodes, m_queuedDisable);
  1849. m_queuedDisable.clear();
  1850. }
  1851. if (!m_queuedEnable.empty())
  1852. {
  1853. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::EnableNodes, m_queuedEnable);
  1854. m_queuedEnable.clear();
  1855. }
  1856. if (!m_queuedVisualDisable.empty())
  1857. {
  1858. GraphUtils::SetNodesEnabledState(m_queuedVisualDisable, RootGraphicsItemEnabledState::ES_Disabled);
  1859. m_queuedVisualDisable.clear();
  1860. }
  1861. if (!m_queuedVisualEnable.empty())
  1862. {
  1863. GraphUtils::SetNodesEnabledState(m_queuedVisualEnable, RootGraphicsItemEnabledState::ES_Enabled);
  1864. m_queuedVisualEnable.clear();
  1865. }
  1866. AZ::SystemTickBus::Handler::BusDisconnect();
  1867. }
  1868. void SceneComponent::ClearSelection()
  1869. {
  1870. if (m_graphicsSceneUi)
  1871. {
  1872. QSignalBlocker signalBlocker(m_graphicsSceneUi.get());
  1873. m_graphicsSceneUi->clearSelection();
  1874. // Always signal the selection change when being told to clear selection.
  1875. // Makes it easier to synchronize selections states across multiple panels.
  1876. OnSelectionChanged();
  1877. }
  1878. }
  1879. void SceneComponent::SetSelectedArea(const AZ::Vector2& topLeft, const AZ::Vector2& topRight)
  1880. {
  1881. if (m_graphicsSceneUi)
  1882. {
  1883. QPainterPath path;
  1884. path.addRect(QRectF{ QPointF {topLeft.GetX(), topLeft.GetY()}, QPointF { topRight.GetX(), topRight.GetY() } });
  1885. m_graphicsSceneUi->setSelectionArea(path);
  1886. }
  1887. }
  1888. void SceneComponent::SelectAll()
  1889. {
  1890. if (m_graphicsSceneUi)
  1891. {
  1892. QPainterPath path;
  1893. path.addRect(m_graphicsSceneUi->sceneRect());
  1894. m_graphicsSceneUi->setSelectionArea(path);
  1895. }
  1896. }
  1897. void SceneComponent::SelectAllRelative(ConnectionType connectionDirection)
  1898. {
  1899. AZStd::vector<AZ::EntityId> seedNodes = GetSelectedNodes();
  1900. AZStd::unordered_set<AZ::EntityId> selectableNodes;
  1901. GraphUtils::FindConnectedNodes(seedNodes, selectableNodes, { connectionDirection });
  1902. AssetEditorRequestBus::Event(GetEditorId(), &AssetEditorRequests::OnSelectionManipulationBegin);
  1903. for (const AZ::EntityId& nodeId : selectableNodes)
  1904. {
  1905. SceneMemberUIRequestBus::Event(nodeId, &SceneMemberUIRequests::SetSelected, true);
  1906. }
  1907. AssetEditorRequestBus::Event(GetEditorId(), &AssetEditorRequests::OnSelectionManipulationEnd);
  1908. }
  1909. void SceneComponent::SelectConnectedNodes()
  1910. {
  1911. AZStd::vector<AZ::EntityId> seedNodes = GetSelectedNodes();
  1912. AZStd::unordered_set<AZ::EntityId> selectableNodes;
  1913. GraphUtils::FindConnectedNodes(seedNodes, selectableNodes, { ConnectionType::CT_Input, ConnectionType::CT_Output });
  1914. AssetEditorRequestBus::Event(GetEditorId(), &AssetEditorRequests::OnSelectionManipulationBegin);
  1915. for (const AZ::EntityId& nodeId : selectableNodes)
  1916. {
  1917. SceneMemberUIRequestBus::Event(nodeId, &SceneMemberUIRequests::SetSelected, true);
  1918. }
  1919. AssetEditorRequestBus::Event(GetEditorId(), &AssetEditorRequests::OnSelectionManipulationEnd);
  1920. }
  1921. bool SceneComponent::HasSelectedItems() const
  1922. {
  1923. return m_graphicsSceneUi ? !m_graphicsSceneUi->selectedItems().isEmpty() : false;
  1924. }
  1925. bool SceneComponent::HasMultipleSelection() const
  1926. {
  1927. return m_graphicsSceneUi ? m_graphicsSceneUi->selectedItems().count() > 1 : false;
  1928. }
  1929. bool SceneComponent::HasCopiableSelection() const
  1930. {
  1931. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1932. bool hasCopiableSelection = false;
  1933. if (m_graphicsSceneUi)
  1934. {
  1935. const QList<QGraphicsItem*> selected(m_graphicsSceneUi->selectedItems());
  1936. for (QGraphicsItem* item : selected)
  1937. {
  1938. auto entry = m_itemLookup.find(item);
  1939. if (entry != m_itemLookup.end())
  1940. {
  1941. AZ::Entity* entity = nullptr;
  1942. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entry->second);
  1943. if (m_graphData.m_nodes.count(entity) > 0)
  1944. {
  1945. hasCopiableSelection = true;
  1946. break;
  1947. }
  1948. else if (m_graphData.m_bookmarkAnchors.count(entity) > 0)
  1949. {
  1950. hasCopiableSelection = true;
  1951. break;
  1952. }
  1953. }
  1954. }
  1955. }
  1956. return hasCopiableSelection;
  1957. }
  1958. bool SceneComponent::HasEntitiesAt(const AZ::Vector2& scenePoint) const
  1959. {
  1960. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1961. bool retVal = false;
  1962. if (m_graphicsSceneUi)
  1963. {
  1964. QList<QGraphicsItem*> itemsThere = m_graphicsSceneUi->items(QPointF(scenePoint.GetX(), scenePoint.GetY()));
  1965. for (QGraphicsItem* item : itemsThere)
  1966. {
  1967. auto entry = m_itemLookup.find(item);
  1968. if (entry != m_itemLookup.end() && entry->second != m_grid)
  1969. {
  1970. retVal = true;
  1971. break;
  1972. }
  1973. }
  1974. }
  1975. return retVal;
  1976. }
  1977. AZStd::vector<AZ::EntityId> SceneComponent::GetSelectedItems() const
  1978. {
  1979. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  1980. AZStd::vector<AZ::EntityId> result;
  1981. if (m_graphicsSceneUi)
  1982. {
  1983. const QList<QGraphicsItem*> selected(m_graphicsSceneUi->selectedItems());
  1984. result.reserve(selected.size());
  1985. for (QGraphicsItem* item : selected)
  1986. {
  1987. auto entry = m_itemLookup.find(item);
  1988. if (entry != m_itemLookup.end())
  1989. {
  1990. result.push_back(entry->second);
  1991. }
  1992. }
  1993. }
  1994. return result;
  1995. }
  1996. QGraphicsScene* SceneComponent::AsQGraphicsScene()
  1997. {
  1998. return m_graphicsSceneUi.get();
  1999. }
  2000. void SceneComponent::CopySelection() const
  2001. {
  2002. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2003. AZStd::vector<AZ::EntityId> entities = GetSelectedItems();
  2004. Copy(entities);
  2005. }
  2006. void SceneComponent::Copy(const AZStd::vector<AZ::EntityId>& selectedItems) const
  2007. {
  2008. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2009. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnCopyBegin);
  2010. GraphSerialization serializationTarget(m_copyMimeType);
  2011. SerializeEntities({ selectedItems.begin(), selectedItems.end() }, serializationTarget);
  2012. SerializeToClipboard(serializationTarget);
  2013. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnCopyEnd);
  2014. }
  2015. void SceneComponent::CutSelection()
  2016. {
  2017. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2018. AZStd::vector<AZ::EntityId> entities = GetSelectedItems();
  2019. Cut(entities);
  2020. }
  2021. void SceneComponent::Cut(const AZStd::vector<AZ::EntityId>& selectedItems)
  2022. {
  2023. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2024. Copy(selectedItems);
  2025. AZStd::unordered_set<AZ::EntityId> deletedItems(selectedItems.begin(), selectedItems.end());
  2026. Delete(deletedItems);
  2027. }
  2028. void SceneComponent::Paste()
  2029. {
  2030. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2031. QPointF pasteCenter = SignalGenericAddPositionUseBegin();
  2032. PasteAt(pasteCenter);
  2033. SignalGenericAddPositionUseEnd();
  2034. }
  2035. void SceneComponent::PasteAt(const QPointF& scenePos)
  2036. {
  2037. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2038. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnPasteBegin);
  2039. {
  2040. QScopedValueRollback pastingRollback(m_isPasting, true);
  2041. if (m_graphicsSceneUi)
  2042. {
  2043. m_graphicsSceneUi->blockSignals(true);
  2044. m_graphicsSceneUi->clearSelection();
  2045. }
  2046. AZ::Vector2 pastePos{ static_cast<float>(scenePos.x()), static_cast<float>(scenePos.y()) };
  2047. QClipboard* clipboard = QApplication::clipboard();
  2048. // Trying to paste unknown data into our scene.
  2049. if (!clipboard->mimeData()->hasFormat(m_copyMimeType.c_str()))
  2050. {
  2051. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnUnknownPaste, scenePos);
  2052. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnPasteEnd);
  2053. return;
  2054. }
  2055. QByteArray byteArray = clipboard->mimeData()->data(m_copyMimeType.c_str());
  2056. GraphSerialization serializationSource(byteArray);
  2057. DeserializeEntities(scenePos, serializationSource);
  2058. if (m_graphicsSceneUi)
  2059. {
  2060. m_graphicsSceneUi->blockSignals(false);
  2061. }
  2062. }
  2063. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnPasteEnd);
  2064. OnSelectionChanged();
  2065. ViewRequestBus::Event(m_viewId, &ViewRequests::RefreshView);
  2066. }
  2067. void SceneComponent::SerializeEntities(const AZStd::unordered_set<AZ::EntityId>& itemIds, GraphSerialization& serializationTarget) const
  2068. {
  2069. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2070. GraphData& serializedEntities = serializationTarget.GetGraphData();
  2071. GraphUtils::ParseMembersForSerialization(serializationTarget, itemIds);
  2072. if (serializedEntities.m_nodes.empty()
  2073. && serializedEntities.m_bookmarkAnchors.empty())
  2074. {
  2075. return;
  2076. }
  2077. // Calculate the position of selected items relative to the position from either the context menu mouse point or the scene center
  2078. AZ::Vector2 aggregatePos = AZ::Vector2::CreateZero();
  2079. // Can't do this with the above listing. Because when nodes get serialized, they may add other nodes to the list.
  2080. // So once we are fully added in, we can figure out our positions.
  2081. for (AZ::Entity* entity : serializedEntities.m_nodes)
  2082. {
  2083. QGraphicsItem* graphicsItem = nullptr;
  2084. SceneMemberUIRequestBus::EventResult(graphicsItem, entity->GetId(), &SceneMemberUIRequests::GetRootGraphicsItem);
  2085. AZ::Vector2 itemPos = AZ::Vector2::CreateZero();
  2086. if (graphicsItem)
  2087. {
  2088. QPointF scenePosition = graphicsItem->scenePos();
  2089. itemPos.SetX(aznumeric_cast<float>(scenePosition.x()));
  2090. itemPos.SetY(aznumeric_cast<float>(scenePosition.y()));
  2091. }
  2092. aggregatePos += itemPos;
  2093. }
  2094. for (AZ::Entity* entity : serializedEntities.m_bookmarkAnchors)
  2095. {
  2096. QGraphicsItem* graphicsItem = nullptr;
  2097. SceneMemberUIRequestBus::EventResult(graphicsItem, entity->GetId(), &SceneMemberUIRequests::GetRootGraphicsItem);
  2098. AZ::Vector2 itemPos = AZ::Vector2::CreateZero();
  2099. if (graphicsItem)
  2100. {
  2101. QPointF scenePosition = graphicsItem->scenePos();
  2102. itemPos.SetX(aznumeric_cast<float>(scenePosition.x()));
  2103. itemPos.SetY(aznumeric_cast<float>(scenePosition.y()));
  2104. }
  2105. aggregatePos += itemPos;
  2106. }
  2107. AZ::Vector2 averagePos = aggregatePos / aznumeric_cast<float>(serializedEntities.m_nodes.size() + serializedEntities.m_bookmarkAnchors.size());
  2108. serializationTarget.SetAveragePosition(averagePos);
  2109. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnEntitiesSerialized, serializationTarget);
  2110. }
  2111. void SceneComponent::DeserializeEntities(const QPointF& scenePoint, const GraphSerialization& serializationSource)
  2112. {
  2113. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2114. AZ::EntityId groupTarget = FindTopmostGroupAtPoint(scenePoint);
  2115. AZ::Vector2 deserializePoint = AZ::Vector2(aznumeric_cast<float>(scenePoint.x()), aznumeric_cast<float>(scenePoint.y()));
  2116. const AZ::Vector2& averagePos = serializationSource.GetAveragePosition();
  2117. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnEntitiesDeserialized, serializationSource);
  2118. const GraphData& pasteSceneData = serializationSource.GetGraphData();
  2119. AZStd::unordered_map< PersistentGraphMemberId, PersistentGraphMemberId > persistentGraphMemberRemapping;
  2120. AZStd::unordered_set<AZ::EntityId> groupableDeserializedEntities;
  2121. for (auto& nodeRef : pasteSceneData.m_nodes)
  2122. {
  2123. AZStd::unique_ptr<AZ::Entity> entity(nodeRef);
  2124. entity->Init();
  2125. entity->Activate();
  2126. AZ::Vector2 prevNodePos;
  2127. GeometryRequestBus::EventResult(prevNodePos, entity->GetId(), &GeometryRequests::GetPosition);
  2128. GeometryRequestBus::Event(entity->GetId(), &GeometryRequests::SetPosition, (prevNodePos - averagePos) + deserializePoint);
  2129. SceneMemberNotificationBus::Event(entity->GetId(), &SceneMemberNotifications::OnSceneMemberDeserialized, GetEntityId(), serializationSource);
  2130. SceneMemberUIRequestBus::Event(entity->GetId(), &SceneMemberUIRequests::SetSelected, true);
  2131. if (Add(entity->GetId(), true))
  2132. {
  2133. entity.release();
  2134. AZ::EntityId nodeId = nodeRef->GetId();
  2135. PersistentGraphMemberId previousId;
  2136. PersistentMemberRequestBus::EventResult(previousId, nodeId, &PersistentMemberRequests::GetPreviousGraphMemberId);
  2137. PersistentGraphMemberId newId;
  2138. PersistentMemberRequestBus::EventResult(newId, nodeId, &PersistentMemberRequests::GetPersistentGraphMemberId);
  2139. persistentGraphMemberRemapping[previousId] = newId;
  2140. if (GraphUtils::IsGroupableElement(nodeId))
  2141. {
  2142. groupableDeserializedEntities.insert(nodeId);
  2143. }
  2144. }
  2145. }
  2146. for (auto& bookmarkRef : pasteSceneData.m_bookmarkAnchors)
  2147. {
  2148. AZStd::unique_ptr<AZ::Entity> entity(bookmarkRef);
  2149. entity->Init();
  2150. entity->Activate();
  2151. AZ::Vector2 prevPos;
  2152. GeometryRequestBus::EventResult(prevPos, entity->GetId(), &GeometryRequests::GetPosition);
  2153. GeometryRequestBus::Event(entity->GetId(), &GeometryRequests::SetPosition, (prevPos - averagePos) + deserializePoint);
  2154. SceneMemberNotificationBus::Event(entity->GetId(), &SceneMemberNotifications::OnSceneMemberDeserialized, GetEntityId(), serializationSource);
  2155. SceneMemberUIRequestBus::Event(entity->GetId(), &SceneMemberUIRequests::SetSelected, true);
  2156. if (Add(entity->GetId()))
  2157. {
  2158. entity.release();
  2159. AZ::EntityId bookmarkId = bookmarkRef->GetId();
  2160. PersistentGraphMemberId previousId;
  2161. PersistentMemberRequestBus::EventResult(previousId, bookmarkId, &PersistentMemberRequests::GetPreviousGraphMemberId);
  2162. PersistentGraphMemberId newId;
  2163. PersistentMemberRequestBus::EventResult(newId, bookmarkId, &PersistentMemberRequests::GetPersistentGraphMemberId);
  2164. persistentGraphMemberRemapping[previousId] = newId;
  2165. if (GraphUtils::IsGroupableElement(bookmarkId))
  2166. {
  2167. groupableDeserializedEntities.insert(bookmarkId);
  2168. }
  2169. }
  2170. }
  2171. // Now go through and recreate all of the connections.
  2172. const AZStd::unordered_multimap<Endpoint, Endpoint>& connectedEndpoints = serializationSource.GetConnectedEndpoints();
  2173. for (const auto& mapPair : connectedEndpoints)
  2174. {
  2175. SlotRequestBus::Event(mapPair.first.GetSlotId(), &SlotRequests::CreateConnectionWithEndpoint, mapPair.second);
  2176. }
  2177. PersistentIdNotificationBus::Event(GetEditorId(), &PersistentIdNotifications::OnPersistentIdsRemapped, persistentGraphMemberRemapping);
  2178. if (groupTarget.IsValid())
  2179. {
  2180. auto groupableIter = groupableDeserializedEntities.begin();
  2181. while (groupableIter != groupableDeserializedEntities.end())
  2182. {
  2183. // Remove any groupable elements that are apart of another group.
  2184. // And just assign everything that is a 'root' element to our new area.
  2185. AZ::EntityId groupId;
  2186. GroupableSceneMemberRequestBus::EventResult(groupId, (*groupableIter), &GroupableSceneMemberRequests::GetGroupId);
  2187. if (groupId.IsValid())
  2188. {
  2189. groupableIter = groupableDeserializedEntities.erase(groupableIter);
  2190. }
  2191. else
  2192. {
  2193. ++groupableIter;
  2194. }
  2195. }
  2196. NodeGroupRequestBus::Event(groupTarget, &NodeGroupRequests::AddElementsToGroup, groupableDeserializedEntities);
  2197. }
  2198. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::PostCreationEvent);
  2199. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnEntitiesDeserializationComplete, serializationSource);
  2200. }
  2201. void SceneComponent::DuplicateSelection()
  2202. {
  2203. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2204. AZStd::vector<AZ::EntityId> entities = GetSelectedItems();
  2205. Duplicate(entities);
  2206. }
  2207. void SceneComponent::DuplicateSelectionAt(const QPointF& scenePos)
  2208. {
  2209. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2210. AZStd::vector<AZ::EntityId> entities = GetSelectedItems();
  2211. DuplicateAt(entities, scenePos);
  2212. }
  2213. void SceneComponent::Duplicate(const AZStd::vector<AZ::EntityId>& itemIds)
  2214. {
  2215. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2216. QPointF duplicateCenter = SignalGenericAddPositionUseBegin();
  2217. DuplicateAt(itemIds, duplicateCenter);
  2218. SignalGenericAddPositionUseEnd();
  2219. }
  2220. void SceneComponent::DuplicateAt(const AZStd::vector<AZ::EntityId>& itemIds, const QPointF& scenePos)
  2221. {
  2222. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2223. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnDuplicateBegin);
  2224. {
  2225. QScopedValueRollback isPastingRollback(m_isPasting, true);
  2226. if (m_graphicsSceneUi)
  2227. {
  2228. m_graphicsSceneUi->blockSignals(true);
  2229. m_graphicsSceneUi->clearSelection();
  2230. }
  2231. GraphSerialization serializationTarget;
  2232. SerializeEntities({ itemIds.begin(), itemIds.end() }, serializationTarget);
  2233. AZStd::vector<char> buffer;
  2234. SerializeToBuffer(serializationTarget, buffer);
  2235. GraphSerialization deserializationTarget(QByteArray(buffer.cbegin(), static_cast<int>(buffer.size())));
  2236. DeserializeEntities(scenePos, deserializationTarget);
  2237. if (m_graphicsSceneUi)
  2238. {
  2239. m_graphicsSceneUi->blockSignals(false);
  2240. }
  2241. }
  2242. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnDuplicateEnd);
  2243. OnSelectionChanged();
  2244. ViewRequestBus::Event(m_viewId, &ViewRequests::RefreshView);
  2245. }
  2246. void SceneComponent::DeleteSelection()
  2247. {
  2248. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2249. if (m_graphicsSceneUi)
  2250. {
  2251. const QList<QGraphicsItem*> selected(m_graphicsSceneUi->selectedItems());
  2252. AZStd::unordered_set<AZ::EntityId> toDelete;
  2253. for (QGraphicsItem* item : selected)
  2254. {
  2255. auto entry = m_itemLookup.find(item);
  2256. if (entry != m_itemLookup.end())
  2257. {
  2258. toDelete.insert(entry->second);
  2259. }
  2260. }
  2261. Delete(toDelete);
  2262. }
  2263. }
  2264. void SceneComponent::Delete(const AZStd::unordered_set<AZ::EntityId>& itemIds)
  2265. {
  2266. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2267. if (itemIds.empty())
  2268. {
  2269. return;
  2270. }
  2271. // Block the graphics scene from sending selection update events as we remove items.
  2272. if (m_graphicsSceneUi)
  2273. {
  2274. if (m_deleteCount == 0)
  2275. {
  2276. m_graphicsSceneUi->blockSignals(true);
  2277. }
  2278. }
  2279. // Need to deal with recursive deleting because of Wrapper Nodes
  2280. ++m_deleteCount;
  2281. SceneMemberBuckets sceneMembers;
  2282. SieveSceneMembers(itemIds, sceneMembers);
  2283. const bool internalConnectionsOnly = false;
  2284. auto nodeConnections = GraphUtils::FindConnectionsForNodes(sceneMembers.m_nodes, internalConnectionsOnly);
  2285. sceneMembers.m_connections.insert(nodeConnections.begin(), nodeConnections.end());
  2286. for (const auto& connection : sceneMembers.m_connections)
  2287. {
  2288. if (Remove(connection))
  2289. {
  2290. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnPreConnectionDeleted, connection);
  2291. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, connection);
  2292. }
  2293. }
  2294. for (const auto& node : sceneMembers.m_nodes)
  2295. {
  2296. NodeRequestBus::Event(node, &NodeRequests::SignalNodeAboutToBeDeleted);
  2297. if (Remove(node))
  2298. {
  2299. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnPreNodeDeleted, node);
  2300. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, node);
  2301. }
  2302. }
  2303. for (const auto& bookmarkAnchor : sceneMembers.m_bookmarkAnchors)
  2304. {
  2305. if (Remove(bookmarkAnchor))
  2306. {
  2307. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, bookmarkAnchor);
  2308. }
  2309. }
  2310. --m_deleteCount;
  2311. if (m_deleteCount == 0)
  2312. {
  2313. if (m_graphicsSceneUi)
  2314. {
  2315. m_graphicsSceneUi->blockSignals(false);
  2316. // Once complete, signal selection is changed
  2317. emit m_graphicsSceneUi->selectionChanged();
  2318. }
  2319. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::PostDeletionEvent);
  2320. }
  2321. }
  2322. void SceneComponent::DeleteGraphData(const GraphData& graphData)
  2323. {
  2324. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2325. AZStd::unordered_set<AZ::EntityId> itemIds;
  2326. graphData.CollectItemIds(itemIds);
  2327. Delete(itemIds);
  2328. }
  2329. void SceneComponent::ClearScene()
  2330. {
  2331. DeleteGraphData(m_graphData);
  2332. AZStd::unordered_map<GraphicsEffectId, QGraphicsItem*> removalPair;
  2333. auto enumerationCallback = [&removalPair](GraphicsEffectRequests* graphicsInterface) -> bool
  2334. {
  2335. QGraphicsItem* graphicsItem = graphicsInterface->AsQGraphicsItem();
  2336. if (graphicsItem)
  2337. {
  2338. removalPair[graphicsInterface->GetEffectId()] = graphicsItem;
  2339. }
  2340. // Enumerate over all handlers
  2341. return true;
  2342. };
  2343. GraphicsEffectRequestBus::EnumerateHandlers(enumerationCallback);
  2344. for (auto effectPair : removalPair)
  2345. {
  2346. DestroyGraphicsItem(effectPair.first, effectPair.second);
  2347. }
  2348. }
  2349. void SceneComponent::SuppressNextContextMenu()
  2350. {
  2351. if (m_graphicsSceneUi)
  2352. {
  2353. m_graphicsSceneUi->SuppressNextContextMenu();
  2354. }
  2355. }
  2356. const AZStd::string& SceneComponent::GetCopyMimeType() const
  2357. {
  2358. return m_copyMimeType;
  2359. }
  2360. void SceneComponent::SetMimeType(const char* mimeType)
  2361. {
  2362. m_mimeDelegateSceneHelper.SetMimeType(mimeType);
  2363. m_copyMimeType = AZStd::string::format("%s::copy", mimeType);
  2364. }
  2365. AZStd::vector<AZ::EntityId> SceneComponent::GetEntitiesAt(const AZ::Vector2& position) const
  2366. {
  2367. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2368. AZStd::vector<AZ::EntityId> result;
  2369. if (m_graphicsSceneUi)
  2370. {
  2371. QList<QGraphicsItem*> itemsThere = m_graphicsSceneUi->items(QPointF(position.GetX(), position.GetY()));
  2372. for (QGraphicsItem* item : itemsThere)
  2373. {
  2374. auto entry = m_itemLookup.find(item);
  2375. if (entry != m_itemLookup.end() && entry->second != m_grid)
  2376. {
  2377. result.emplace_back(AZStd::move(entry->second));
  2378. }
  2379. }
  2380. }
  2381. return result;
  2382. }
  2383. AZStd::vector<AZ::EntityId> SceneComponent::GetEntitiesInRect(const QRectF& rect, Qt::ItemSelectionMode mode) const
  2384. {
  2385. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2386. AZStd::vector<AZ::EntityId> result;
  2387. if (m_graphicsSceneUi)
  2388. {
  2389. QList<QGraphicsItem*> itemsThere = m_graphicsSceneUi->items(rect, mode);
  2390. for (QGraphicsItem* item : itemsThere)
  2391. {
  2392. auto entry = m_itemLookup.find(item);
  2393. if (entry != m_itemLookup.end() && entry->second != m_grid)
  2394. {
  2395. result.emplace_back(AZStd::move(entry->second));
  2396. }
  2397. }
  2398. }
  2399. return result;
  2400. }
  2401. AZStd::vector<Endpoint> SceneComponent::GetEndpointsInRect(const QRectF& rect) const
  2402. {
  2403. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2404. AZStd::vector<Endpoint> result;
  2405. AZStd::vector<AZ::EntityId> entitiesThere = GetEntitiesInRect(rect, Qt::ItemSelectionMode::IntersectsItemShape);
  2406. for (AZ::EntityId nodeId : entitiesThere)
  2407. {
  2408. if (NodeRequestBus::FindFirstHandler(nodeId) != nullptr)
  2409. {
  2410. AZStd::vector<AZ::EntityId> slotIds;
  2411. NodeRequestBus::EventResult(slotIds, nodeId, &NodeRequestBus::Events::GetSlotIds);
  2412. for (AZ::EntityId slotId : slotIds)
  2413. {
  2414. QPointF point;
  2415. SlotUIRequestBus::EventResult(point, slotId, &SlotUIRequestBus::Events::GetConnectionPoint);
  2416. if (rect.contains(point))
  2417. {
  2418. result.emplace_back(Endpoint(nodeId, slotId));
  2419. }
  2420. }
  2421. }
  2422. }
  2423. AZStd::sort(result.begin(), result.end(), [&rect](Endpoint a, Endpoint b) {
  2424. QPointF pointA;
  2425. SlotUIRequestBus::EventResult(pointA, a.GetSlotId(), &SlotUIRequestBus::Events::GetConnectionPoint);
  2426. QPointF pointB;
  2427. SlotUIRequestBus::EventResult(pointB, b.GetSlotId(), &SlotUIRequestBus::Events::GetConnectionPoint);
  2428. return (rect.center() - pointA).manhattanLength() < (rect.center() - pointB).manhattanLength();
  2429. });
  2430. return result;
  2431. }
  2432. void SceneComponent::RegisterView(const AZ::EntityId& viewId)
  2433. {
  2434. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2435. if (m_activateScene)
  2436. {
  2437. m_activateScene = false;
  2438. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPushPreventUndoStateUpdate);
  2439. ActivateItems(m_graphData.m_nodes);
  2440. ActivateItems(m_graphData.m_connections);
  2441. ActivateItems(m_graphData.m_bookmarkAnchors);
  2442. NotifyConnectedSlots();
  2443. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnStylesChanged); // Forces activated elements to refresh their visual elements.
  2444. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPopPreventUndoStateUpdate);
  2445. }
  2446. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnViewRegistered);
  2447. if (!m_viewId.IsValid() || m_viewId == viewId)
  2448. {
  2449. m_viewId = viewId;
  2450. EditorId editorId;
  2451. ViewRequestBus::EventResult(editorId, viewId, &ViewRequests::GetEditorId);
  2452. SetEditorId(editorId);
  2453. ViewNotificationBus::Handler::BusConnect(m_viewId);
  2454. ViewRequestBus::Event(m_viewId, &ViewRequests::SetViewParams, m_viewParams);
  2455. }
  2456. else
  2457. {
  2458. AZ_Error("Scene", false, "Trying to register scene to two different views.");
  2459. }
  2460. }
  2461. void SceneComponent::RemoveView(const AZ::EntityId& viewId)
  2462. {
  2463. if (m_viewId == viewId)
  2464. {
  2465. m_editorId = EditorId();
  2466. m_viewId.SetInvalid();
  2467. ViewNotificationBus::Handler::BusDisconnect();
  2468. }
  2469. else
  2470. {
  2471. AZ_Error("Scene", !m_viewId.IsValid(), "Trying to unregister scene from the wrong view.");
  2472. }
  2473. }
  2474. ViewId SceneComponent::GetViewId() const
  2475. {
  2476. return m_viewId;
  2477. }
  2478. void SceneComponent::DispatchSceneDropEvent(const AZ::Vector2& scenePos, const QMimeData* mimeData)
  2479. {
  2480. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2481. QPointF scenePoint(scenePos.GetX(), scenePos.GetY());
  2482. for (const AZ::EntityId& delegateId : m_delegates)
  2483. {
  2484. bool isInterested;
  2485. SceneMimeDelegateHandlerRequestBus::EventResult(isInterested, delegateId, &SceneMimeDelegateHandlerRequests::IsInterestedInMimeData, GetEntityId(), mimeData);
  2486. if (isInterested)
  2487. {
  2488. SceneMimeDelegateHandlerRequestBus::Event(delegateId, &SceneMimeDelegateHandlerRequests::HandleDrop, GetEntityId(), scenePoint, mimeData);
  2489. }
  2490. }
  2491. // Force the focus onto the GraphicsScene after a drop.
  2492. AZ::EntityId viewId = GetViewId();
  2493. QTimer::singleShot(0, [viewId]()
  2494. {
  2495. GraphCanvasGraphicsView* graphicsView = nullptr;
  2496. ViewRequestBus::EventResult(graphicsView, viewId, &ViewRequests::AsGraphicsView);
  2497. if (graphicsView)
  2498. {
  2499. graphicsView->setFocus(Qt::FocusReason::MouseFocusReason);
  2500. }
  2501. });
  2502. }
  2503. bool SceneComponent::AddGraphData(const GraphData& graphData)
  2504. {
  2505. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2506. bool success = true;
  2507. for (const AZStd::unordered_set<AZ::Entity*>& entitySet : { graphData.m_nodes, graphData.m_bookmarkAnchors, graphData.m_connections })
  2508. {
  2509. for (AZ::Entity* itemRef : entitySet)
  2510. {
  2511. if (itemRef->GetState() == AZ::Entity::State::Init)
  2512. {
  2513. itemRef->Activate();
  2514. }
  2515. success = Add(itemRef->GetId()) && success;
  2516. }
  2517. }
  2518. return success;
  2519. }
  2520. void SceneComponent::RemoveGraphData(const GraphData& graphData)
  2521. {
  2522. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2523. AZStd::unordered_set<AZ::EntityId> itemIds;
  2524. graphData.CollectItemIds(itemIds);
  2525. for (const AZ::EntityId& itemId : itemIds)
  2526. {
  2527. Remove(itemId);
  2528. }
  2529. }
  2530. void SceneComponent::SetDragSelectionType(DragSelectionType selectionType)
  2531. {
  2532. m_dragSelectionType = selectionType;
  2533. }
  2534. void SceneComponent::SignalDragSelectStart()
  2535. {
  2536. m_isDragSelecting = true;
  2537. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnDragSelectStart);
  2538. }
  2539. void SceneComponent::SignalDragSelectEnd()
  2540. {
  2541. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnDragSelectEnd);
  2542. m_isDragSelecting = false;
  2543. }
  2544. bool SceneComponent::IsDragSelecting() const
  2545. {
  2546. return m_isDragSelecting;
  2547. }
  2548. void SceneComponent::SignalConnectionDragBegin()
  2549. {
  2550. // Bit of a hack to get the connections to play nicely with some signalling.
  2551. if (HasSelectedItems())
  2552. {
  2553. ClearSelection();
  2554. }
  2555. else
  2556. {
  2557. OnSelectionChanged();
  2558. }
  2559. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnConnectionDragBegin);
  2560. m_isDraggingConnection = true;
  2561. }
  2562. void SceneComponent::SignalConnectionDragEnd()
  2563. {
  2564. m_isDraggingConnection = false;
  2565. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnConnectionDragEnd);
  2566. }
  2567. bool SceneComponent::IsDraggingConnection() const
  2568. {
  2569. return m_isDraggingConnection;
  2570. }
  2571. void SceneComponent::SignalDesplice()
  2572. {
  2573. CancelNudging();
  2574. }
  2575. QRectF SceneComponent::GetSelectedSceneBoundingArea() const
  2576. {
  2577. QRectF boundingRect;
  2578. for (const auto& sceneMemberList : { m_graphData.m_nodes, m_graphData.m_bookmarkAnchors })
  2579. {
  2580. for (const auto& sceneMember : sceneMemberList)
  2581. {
  2582. QGraphicsItem* sceneItem = nullptr;
  2583. VisualRequestBus::EventResult(sceneItem, sceneMember->GetId(), &VisualRequests::AsGraphicsItem);
  2584. if (sceneItem && sceneItem->isSelected())
  2585. {
  2586. if (boundingRect.isEmpty())
  2587. {
  2588. boundingRect = sceneItem->sceneBoundingRect();
  2589. }
  2590. else
  2591. {
  2592. boundingRect |= sceneItem->sceneBoundingRect();
  2593. }
  2594. }
  2595. }
  2596. }
  2597. return boundingRect;
  2598. }
  2599. QRectF SceneComponent::GetSceneBoundingArea() const
  2600. {
  2601. QRectF boundingRect;
  2602. for (const auto& sceneMemberList : { m_graphData.m_nodes, m_graphData.m_bookmarkAnchors })
  2603. {
  2604. for (const auto& sceneMember : sceneMemberList)
  2605. {
  2606. QGraphicsItem* sceneItem = nullptr;
  2607. VisualRequestBus::EventResult(sceneItem, sceneMember->GetId(), &VisualRequests::AsGraphicsItem);
  2608. if (sceneItem)
  2609. {
  2610. if (boundingRect.isEmpty())
  2611. {
  2612. boundingRect = sceneItem->sceneBoundingRect();
  2613. }
  2614. else
  2615. {
  2616. boundingRect |= sceneItem->sceneBoundingRect();
  2617. }
  2618. }
  2619. }
  2620. }
  2621. return boundingRect;
  2622. }
  2623. void SceneComponent::SignalLoadStart()
  2624. {
  2625. m_isLoading = true;
  2626. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnGraphLoadBegin);
  2627. }
  2628. void SceneComponent::SignalLoadEnd()
  2629. {
  2630. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnGraphLoadComplete);
  2631. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::PostOnGraphLoadComplete);
  2632. m_isLoading = false;
  2633. }
  2634. bool SceneComponent::IsLoading() const
  2635. {
  2636. return m_isLoading;
  2637. }
  2638. bool SceneComponent::IsPasting() const
  2639. {
  2640. return m_isPasting;
  2641. }
  2642. void SceneComponent::RemoveUnusedNodes()
  2643. {
  2644. AZStd::vector< NodeId > nodeIds = GetNodes();
  2645. AZStd::unordered_set< AZ::EntityId > unusedIds;
  2646. AZStd::unordered_set< NodeId > wrapperNodes;
  2647. for (const NodeId& nodeId : nodeIds)
  2648. {
  2649. // Going to skip node groups for now.
  2650. if (GraphUtils::IsCollapsedNodeGroup(nodeId)
  2651. || GraphUtils::IsNodeGroup(nodeId)
  2652. || GraphUtils::IsComment(nodeId))
  2653. {
  2654. continue;
  2655. }
  2656. bool hasConnections = false;
  2657. NodeRequestBus::EventResult(hasConnections, nodeId, &NodeRequests::HasConnections);
  2658. if (!hasConnections)
  2659. {
  2660. if (GraphUtils::IsWrapperNode(nodeId))
  2661. {
  2662. wrapperNodes.insert(nodeId);
  2663. }
  2664. else
  2665. {
  2666. unusedIds.insert(nodeId);
  2667. }
  2668. }
  2669. }
  2670. for (const NodeId& wrapperNodeId : wrapperNodes)
  2671. {
  2672. AZStd::vector< NodeId > wrappedNodes;
  2673. WrapperNodeRequestBus::EventResult(wrappedNodes, wrapperNodeId, &WrapperNodeRequests::GetWrappedNodeIds);
  2674. bool canDelete = true;
  2675. for (const NodeId& wrappedNodeId : wrappedNodes)
  2676. {
  2677. if (unusedIds.count(wrappedNodeId) == 0)
  2678. {
  2679. canDelete = false;
  2680. break;
  2681. }
  2682. }
  2683. if (canDelete)
  2684. {
  2685. unusedIds.insert(wrapperNodeId);
  2686. }
  2687. }
  2688. {
  2689. ScopedGraphUndoBlocker undoBlocker(GetEntityId());
  2690. Delete(unusedIds);
  2691. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::OnRemoveUnusedNodes);
  2692. }
  2693. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestUndoPoint);
  2694. }
  2695. void SceneComponent::HandleProposalDaisyChainWithGroup(const NodeId& startNode, SlotType slotType, ConnectionType connectionType, const QPoint& screenPoint, const QPointF& focusPoint, AZ::EntityId groupTarget)
  2696. {
  2697. AZ::Vector2 stepAmount = GraphUtils::FindMinorStep(GetEntityId());
  2698. Endpoint newEndpoint;
  2699. AZ::EntityId connectionId;
  2700. AZStd::vector< SlotId > slotIds;
  2701. NodeRequestBus::EventResult(slotIds, startNode, &NodeRequests::GetVisibleSlotIds);
  2702. for (const SlotId& slotId : slotIds)
  2703. {
  2704. if (!GraphUtils::IsSlot(slotId, slotType, connectionType))
  2705. {
  2706. continue;
  2707. }
  2708. newEndpoint = Endpoint(startNode, slotId);
  2709. break;
  2710. }
  2711. if (newEndpoint.IsValid())
  2712. {
  2713. AZ::EntityId newConnectionId;
  2714. SlotRequestBus::EventResult(newConnectionId, newEndpoint.GetSlotId(), &SlotRequests::DisplayConnection);
  2715. if (newConnectionId.IsValid())
  2716. {
  2717. QPointF connectionPoint;
  2718. SlotUIRequestBus::EventResult(connectionPoint, newEndpoint.GetSlotId(), &SlotUIRequests::GetConnectionPoint);
  2719. QPointF jut;
  2720. SlotUIRequestBus::EventResult(jut, newEndpoint.GetSlotId(), &SlotUIRequests::GetJutDirection);
  2721. connectionPoint.setX(connectionPoint.x() + 2.0f * stepAmount.GetX() * jut.x());
  2722. // Because the size of the nodes are clamped to a size, they don't get resized until they are rendered.
  2723. // This makes doing this sort of fine tuned positioning weird. Since it does it based on the wrong size, then it resizes
  2724. // and ruins everything. Going to just hack this for nowt o give it an extra half step if it's going backwards(which is where this case matters)
  2725. if (jut.x() < 0)
  2726. {
  2727. connectionPoint.setX(connectionPoint.x() - stepAmount.GetX() * 0.5f);
  2728. }
  2729. connectionPoint.setY(connectionPoint.y() + 2.0f * stepAmount.GetY() * jut.y());
  2730. // Delta vector we need to move the scene by
  2731. QPointF repositioning = connectionPoint - focusPoint;
  2732. ViewRequestBus::Event(GetViewId(), &ViewRequests::PanSceneBy, repositioning, AZStd::chrono::milliseconds(250));
  2733. ConnectionRequestBus::Event(newConnectionId, &ConnectionRequests::ChainProposalCreation, connectionPoint, screenPoint, groupTarget);
  2734. }
  2735. }
  2736. }
  2737. void SceneComponent::StartNudging(const AZStd::unordered_set<AZ::EntityId>& fixedNodes)
  2738. {
  2739. if (m_enableNudging)
  2740. {
  2741. m_nudgingController.StartNudging(fixedNodes);
  2742. }
  2743. }
  2744. void SceneComponent::FinalizeNudging()
  2745. {
  2746. if (m_enableNudging)
  2747. {
  2748. m_nudgingController.FinalizeNudging();
  2749. }
  2750. }
  2751. void SceneComponent::CancelNudging()
  2752. {
  2753. if (m_enableNudging)
  2754. {
  2755. m_nudgingController.CancelNudging();
  2756. }
  2757. }
  2758. AZ::EntityId SceneComponent::FindTopmostGroupAtPoint(QPointF scenePoint)
  2759. {
  2760. return FindGroupTarget(scenePoint);
  2761. }
  2762. void SceneComponent::RemoveUnusedElements()
  2763. {
  2764. {
  2765. ScopedGraphUndoBlocker undoBlocker(GetEntityId());
  2766. RemoveUnusedNodes();
  2767. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::OnRemoveUnusedElements);
  2768. }
  2769. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestUndoPoint);
  2770. }
  2771. QPointF SceneComponent::SignalGenericAddPositionUseBegin()
  2772. {
  2773. m_allowReset = false;
  2774. return GetViewCenterScenePoint() + m_genericAddOffset;
  2775. }
  2776. void SceneComponent::SignalGenericAddPositionUseEnd()
  2777. {
  2778. AZ::Vector2 minorPitch;
  2779. GridRequestBus::EventResult(minorPitch, m_grid, &GridRequests::GetMinorPitch);
  2780. // Don't want to shift it diagonally, because we also shift things diagonally when we drag/drop in stuff
  2781. // So we'll just move it straight down.
  2782. m_genericAddOffset += QPointF(0, minorPitch.GetY() * 2);
  2783. m_allowReset = true;
  2784. }
  2785. bool SceneComponent::AllowContextMenu() const
  2786. {
  2787. return !IsDragSelecting() && !IsDraggingConnection();
  2788. }
  2789. bool SceneComponent::OnMousePress(const AZ::EntityId& sourceId, const QGraphicsSceneMouseEvent* event)
  2790. {
  2791. if (event->button() == Qt::LeftButton && sourceId != m_grid)
  2792. {
  2793. m_enableSpliceTracking = false;
  2794. m_enableNodeDragConnectionSpliceTracking = false;
  2795. m_enableNodeDragCouplingTracking = false;
  2796. m_enableNodeChainDragConnectionSpliceTracking = false;
  2797. m_spliceTarget.SetInvalid();
  2798. m_pressedEntity = sourceId;
  2799. m_gestureSceneHelper.TrackElement(m_pressedEntity);
  2800. GeometryRequestBus::EventResult(m_originalPosition, m_pressedEntity, &GeometryRequests::GetPosition);
  2801. }
  2802. return false;
  2803. }
  2804. bool SceneComponent::OnMouseRelease(const AZ::EntityId& /*sourceId*/, const QGraphicsSceneMouseEvent* /*event*/)
  2805. {
  2806. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2807. if (m_isDraggingEntity)
  2808. {
  2809. {
  2810. ScopedGraphUndoBlocker undoBlocker(GetEntityId());
  2811. for (AZ::EntityId groupableElement : m_draggedGroupableElements)
  2812. {
  2813. GroupableSceneMemberRequestBus::Event(groupableElement, &GroupableSceneMemberRequests::RemoveFromGroup);
  2814. }
  2815. if (m_dragTargetGroup.IsValid())
  2816. {
  2817. NodeGroupRequestBus::Event(m_dragTargetGroup, &NodeGroupRequests::AddElementsToGroup, m_draggedGroupableElements);
  2818. const bool growGroupOnly = true;
  2819. NodeGroupRequestBus::Event(m_dragTargetGroup, &NodeGroupRequests::ResizeGroupToElements, growGroupOnly);
  2820. }
  2821. m_dragTargetGroup.SetInvalid();
  2822. m_forcedLayerStateSetter.ResetStateSetter();
  2823. m_forcedGroupDisplayStateStateSetter.ResetStateSetter();
  2824. m_draggedGroupableElements.clear();
  2825. m_ignoredDragTargets.clear();
  2826. }
  2827. // Set the dragging element after the group resize. Otherwise the group will send out a position change, and remove the thing
  2828. // it just attempted to position.
  2829. m_isDraggingEntity = false;
  2830. AZ::Vector2 finalPosition;
  2831. GeometryRequestBus::EventResult(finalPosition, m_pressedEntity, &GeometryRequests::GetPosition);
  2832. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSceneMemberDragComplete);
  2833. if (m_forceDragReleaseUndo || !finalPosition.IsClose(m_originalPosition))
  2834. {
  2835. m_forceDragReleaseUndo = false;
  2836. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestUndoPoint);
  2837. }
  2838. }
  2839. m_isDraggingEntity = false;
  2840. m_dragTargetGroup.SetInvalid();
  2841. m_enableSpliceTracking = false;
  2842. m_spliceTimer.stop();
  2843. m_spliceTarget.SetInvalid();
  2844. m_spliceTargetDisplayStateStateSetter.ResetStateSetter();
  2845. m_pressedEntityDisplayStateStateSetter.ResetStateSetter();
  2846. m_couplingEntityDisplayStateStateSetter.ResetStateSetter();
  2847. m_gestureSceneHelper.StopTrack();
  2848. m_pressedEntity.SetInvalid();
  2849. return false;
  2850. }
  2851. void SceneComponent::OnPositionChanged(const AZ::EntityId& itemId, const AZ::Vector2& position)
  2852. {
  2853. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  2854. if (m_pressedEntity.IsValid()
  2855. && itemId == m_pressedEntity)
  2856. {
  2857. if (!m_isDraggingEntity)
  2858. {
  2859. m_isDraggingEntity = true;
  2860. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSceneMemberDragBegin);
  2861. AssetEditorSettingsRequestBus::EventResult(m_enableNodeDragConnectionSpliceTracking, GetEditorId(), &AssetEditorSettingsRequests::IsDragConnectionSpliceEnabled);
  2862. AssetEditorSettingsRequestBus::EventResult(m_enableNodeDragCouplingTracking, GetEditorId(), &AssetEditorSettingsRequests::IsDragNodeCouplingEnabled);
  2863. AZStd::vector< AZ::EntityId > selectedEntities = GetSelectedNodes();
  2864. // Precache all of the groups so we can filter out elements that belong to them in our final set.
  2865. AZStd::unordered_set< AZ::EntityId > selectedGroups;
  2866. for (AZ::EntityId selectedId : selectedEntities)
  2867. {
  2868. if (GraphUtils::IsNodeGroup(selectedId))
  2869. {
  2870. m_ignoredDragTargets.insert(selectedId);
  2871. selectedGroups.insert(selectedId);
  2872. }
  2873. }
  2874. for (AZ::EntityId selectedId : selectedEntities)
  2875. {
  2876. if (GraphUtils::IsGroupableElement(selectedId) && !GraphUtils::IsNodeWrapped(selectedId))
  2877. {
  2878. // If you are already grouped. Sanity check if your parent group is being moved as well. If it is, don't do anything.
  2879. // Otherwise, remove yourself from that group and insert yourself into the overall list.
  2880. AZ::EntityId owningGroup;
  2881. GroupableSceneMemberRequestBus::EventResult(owningGroup, selectedId, &GroupableSceneMemberRequests::GetGroupId);
  2882. if (owningGroup.IsValid())
  2883. {
  2884. AZ::EntityId previousGroup;
  2885. while (owningGroup.IsValid())
  2886. {
  2887. if (selectedGroups.find(owningGroup) != selectedGroups.end())
  2888. {
  2889. break;
  2890. }
  2891. GroupableSceneMemberRequestBus::EventResult(owningGroup, owningGroup, &GroupableSceneMemberRequests::GetGroupId);
  2892. }
  2893. if (!owningGroup.IsValid())
  2894. {
  2895. m_draggedGroupableElements.insert(selectedId);
  2896. }
  2897. }
  2898. else
  2899. {
  2900. m_draggedGroupableElements.insert(selectedId);
  2901. }
  2902. }
  2903. }
  2904. if (GraphUtils::IsConnectableNode(m_pressedEntity) && (m_enableNodeDragConnectionSpliceTracking || m_enableNodeDragCouplingTracking)
  2905. || (GraphUtils::IsNodeGroup(m_pressedEntity) && m_enableNodeDragConnectionSpliceTracking))
  2906. {
  2907. if (GraphUtils::IsNodeGroup(m_pressedEntity))
  2908. {
  2909. NodeGroupRequestBus::Event(m_pressedEntity, &NodeGroupRequests::FindGroupedElements, selectedEntities);
  2910. }
  2911. m_inputCouplingTarget.SetInvalid();
  2912. m_outputCouplingTarget.SetInvalid();
  2913. m_couplingTarget.SetInvalid();
  2914. m_selectedSubGraph.Clear();
  2915. SubGraphParsingConfig config;
  2916. SubGraphParsingResult subGraphResult = GraphUtils::ParseSceneMembersIntoSubGraphs(selectedEntities, config);
  2917. if (subGraphResult.m_subGraphs.size() == 1)
  2918. {
  2919. m_enableNodeChainDragConnectionSpliceTracking = true;
  2920. m_selectedSubGraph = subGraphResult.m_subGraphs.front();
  2921. }
  2922. else
  2923. {
  2924. m_enableNodeChainDragConnectionSpliceTracking = false;
  2925. }
  2926. if (m_enableNodeDragCouplingTracking)
  2927. {
  2928. if (GraphUtils::IsNodeGroup(m_pressedEntity))
  2929. {
  2930. m_enableNodeDragCouplingTracking = false;
  2931. }
  2932. else if (selectedEntities.size() > 1)
  2933. {
  2934. m_selectedSubGraph.Clear();
  2935. SubGraphParsingConfig config2;
  2936. config2.m_createNonConnectableSubGraph = true;
  2937. SubGraphParsingResult subGraphResult2 = GraphUtils::ParseSceneMembersIntoSubGraphs(selectedEntities, config2);
  2938. if (subGraphResult2.m_subGraphs.size() == 1)
  2939. {
  2940. m_selectedSubGraph = subGraphResult2.m_subGraphs.front();
  2941. if (m_selectedSubGraph.m_entryNodes.size() == 1
  2942. && m_selectedSubGraph.m_exitNodes.size() == 1)
  2943. {
  2944. m_enableNodeDragCouplingTracking = true;
  2945. m_inputCouplingTarget = (*m_selectedSubGraph.m_entryNodes.begin());
  2946. m_outputCouplingTarget = (*m_selectedSubGraph.m_exitNodes.begin());
  2947. }
  2948. else
  2949. {
  2950. for (auto entryNode : m_selectedSubGraph.m_entryNodes)
  2951. {
  2952. if (entryNode == m_pressedEntity)
  2953. {
  2954. m_enableNodeDragCouplingTracking = true;
  2955. m_inputCouplingTarget = entryNode;
  2956. }
  2957. }
  2958. for (auto entryNode : m_selectedSubGraph.m_exitNodes)
  2959. {
  2960. if (entryNode == m_pressedEntity)
  2961. {
  2962. m_enableNodeDragCouplingTracking = true;
  2963. m_outputCouplingTarget = entryNode;
  2964. }
  2965. }
  2966. }
  2967. }
  2968. else
  2969. {
  2970. m_enableNodeDragCouplingTracking = false;
  2971. }
  2972. }
  2973. else if (selectedEntities.size() == 1)
  2974. {
  2975. m_enableSpliceTracking = true;
  2976. m_inputCouplingTarget = m_pressedEntity;
  2977. m_outputCouplingTarget = m_pressedEntity;
  2978. }
  2979. else
  2980. {
  2981. m_enableSpliceTracking = false;
  2982. m_inputCouplingTarget.SetInvalid();
  2983. m_outputCouplingTarget.SetInvalid();
  2984. }
  2985. }
  2986. m_enableSpliceTracking = m_enableNodeChainDragConnectionSpliceTracking || m_enableNodeDragCouplingTracking;
  2987. if (m_enableSpliceTracking)
  2988. {
  2989. m_pressedEntityDisplayStateStateSetter.ResetStateSetter();
  2990. StateController<RootGraphicsItemDisplayState>* stateController;
  2991. RootGraphicsItemRequestBus::EventResult(stateController, m_pressedEntity, &RootGraphicsItemRequests::GetDisplayStateStateController);
  2992. m_pressedEntityDisplayStateStateSetter.AddStateController(stateController);
  2993. }
  2994. }
  2995. GraphCanvasGraphicsView* graphicsView = nullptr;
  2996. ViewRequestBus::EventResult(graphicsView, m_viewId, &ViewRequests::AsGraphicsView);
  2997. QPointF scenePoint;
  2998. if (graphicsView)
  2999. {
  3000. QPointF cursorPoint = QCursor::pos();
  3001. QPointF viewPoint = graphicsView->mapFromGlobal(cursorPoint.toPoint());
  3002. scenePoint = graphicsView->mapToScene(viewPoint.toPoint());
  3003. DetermineDragGroupTarget(scenePoint);
  3004. }
  3005. }
  3006. }
  3007. if (!GraphUtils::IsConnection(itemId))
  3008. {
  3009. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnNodePositionChanged, itemId, position);
  3010. if (m_allowReset)
  3011. {
  3012. m_genericAddOffset.setX(0);
  3013. m_genericAddOffset.setY(0);
  3014. }
  3015. }
  3016. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSceneMemberPositionChanged, itemId, position);
  3017. if (m_graphicsSceneUi)
  3018. {
  3019. m_graphicsSceneUi->update();
  3020. }
  3021. }
  3022. void SceneComponent::OnEscape()
  3023. {
  3024. ClearSelection();
  3025. }
  3026. void SceneComponent::OnViewParamsChanged(const ViewParams& viewParams)
  3027. {
  3028. m_genericAddOffset.setX(0);
  3029. m_genericAddOffset.setY(0);
  3030. m_viewParams = viewParams;
  3031. }
  3032. void SceneComponent::AddDelegate(const AZ::EntityId& delegateId)
  3033. {
  3034. m_delegates.insert(delegateId);
  3035. }
  3036. void SceneComponent::RemoveDelegate(const AZ::EntityId& delegateId)
  3037. {
  3038. m_delegates.erase(delegateId);
  3039. }
  3040. AZ::u32 SceneComponent::GetNewBookmarkCounter()
  3041. {
  3042. return ++m_bookmarkCounter;
  3043. }
  3044. void SceneComponent::OnStylesLoaded()
  3045. {
  3046. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnStylesChanged);
  3047. }
  3048. void SceneComponent::OnSettingsChanged()
  3049. {
  3050. m_gestureSceneHelper.OnSettingsChanged();
  3051. AssetEditorSettingsRequestBus::EventResult(m_enableNudging, GetEditorId(), &AssetEditorSettingsRequests::IsNodeNudgingEnabled);
  3052. if (!m_enableNudging)
  3053. {
  3054. m_nudgingController.CancelNudging();
  3055. }
  3056. }
  3057. void SceneComponent::ConfigureAndAddGraphicsEffect(GraphicsEffectInterface* graphicsEffect)
  3058. {
  3059. graphicsEffect->SetGraphId(GetEntityId());
  3060. graphicsEffect->SetEditorId(GetEditorId());
  3061. QGraphicsItem* graphicsItem = graphicsEffect->AsQGraphicsItem();
  3062. m_graphicsSceneUi->addItem(graphicsItem);
  3063. }
  3064. void SceneComponent::OnSceneDragEnter(const QMimeData* mimeData)
  3065. {
  3066. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3067. m_activeDelegates.clear();
  3068. for (const AZ::EntityId& delegateId : m_delegates)
  3069. {
  3070. bool isInterested = false;
  3071. SceneMimeDelegateHandlerRequestBus::EventResult(isInterested, delegateId, &SceneMimeDelegateHandlerRequests::IsInterestedInMimeData, GetEntityId(), mimeData);
  3072. if (isInterested)
  3073. {
  3074. m_activeDelegates.insert(delegateId);
  3075. }
  3076. }
  3077. }
  3078. void SceneComponent::OnSceneDragMoveEvent(const QPointF& scenePoint, const QMimeData* mimeData)
  3079. {
  3080. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3081. for (const AZ::EntityId& delegateId : m_activeDelegates)
  3082. {
  3083. SceneMimeDelegateHandlerRequestBus::Event(delegateId, &SceneMimeDelegateHandlerRequests::HandleMove, GetEntityId(), scenePoint, mimeData);
  3084. }
  3085. }
  3086. void SceneComponent::OnSceneDropEvent(const QPointF& scenePoint, const QMimeData* mimeData)
  3087. {
  3088. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3089. for (const AZ::EntityId& dropHandler : m_activeDelegates)
  3090. {
  3091. SceneMimeDelegateHandlerRequestBus::Event(dropHandler, &SceneMimeDelegateHandlerRequests::HandleDrop, GetEntityId(), scenePoint, mimeData);
  3092. }
  3093. AZ::EntityId viewId = GetViewId();
  3094. // Force the focus onto the GraphicsView after a drop.
  3095. QTimer::singleShot(0, [viewId]()
  3096. {
  3097. GraphCanvasGraphicsView* graphicsView = nullptr;
  3098. ViewRequestBus::EventResult(graphicsView, viewId, &ViewRequests::AsGraphicsView);
  3099. if (graphicsView)
  3100. {
  3101. graphicsView->setFocus(Qt::FocusReason::MouseFocusReason);
  3102. }
  3103. });
  3104. }
  3105. void SceneComponent::OnSceneDragExit(const QMimeData* mimeData)
  3106. {
  3107. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3108. for (const AZ::EntityId& dropHandler : m_activeDelegates)
  3109. {
  3110. SceneMimeDelegateHandlerRequestBus::Event(dropHandler, &SceneMimeDelegateHandlerRequests::HandleLeave, GetEntityId(), mimeData);
  3111. }
  3112. m_activeDelegates.clear();
  3113. }
  3114. bool SceneComponent::HasActiveMimeDelegates() const
  3115. {
  3116. return !m_activeDelegates.empty();
  3117. }
  3118. template<typename Container>
  3119. void SceneComponent::InitItems(const Container& entities) const
  3120. {
  3121. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3122. for (const auto& entityRef : entities)
  3123. {
  3124. AZ::Entity* entity = entityRef;
  3125. if (entity)
  3126. {
  3127. if (entity->GetState() == AZ::Entity::State::Constructed)
  3128. {
  3129. entity->Init();
  3130. }
  3131. }
  3132. }
  3133. }
  3134. template<typename Container>
  3135. void SceneComponent::ActivateItems(const Container& entities)
  3136. {
  3137. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3138. for (const auto& entityRef : entities)
  3139. {
  3140. AZ::Entity* entity = entityRef;
  3141. if (entity)
  3142. {
  3143. if (entity->GetState() == AZ::Entity::State::Init)
  3144. {
  3145. entity->Activate();
  3146. }
  3147. AddSceneMember(entity->GetId());
  3148. }
  3149. }
  3150. }
  3151. template<typename Container>
  3152. void SceneComponent::DeactivateItems(const Container& entities)
  3153. {
  3154. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3155. for (const auto& entityRef : entities)
  3156. {
  3157. AZ::Entity* entity = entityRef;
  3158. if (entity)
  3159. {
  3160. if (entity->GetState() == AZ::Entity::State::Active)
  3161. {
  3162. GeometryNotificationBus::MultiHandler::BusDisconnect(entity->GetId());
  3163. QGraphicsItem* item = nullptr;
  3164. SceneMemberUIRequestBus::EventResult(item, entity->GetId(), &SceneMemberUIRequests::GetRootGraphicsItem);
  3165. SceneMemberRequestBus::Event(entity->GetId(), &SceneMemberRequests::ClearScene, GetEntityId());
  3166. RemoveItemFromScene(item);
  3167. entity->Deactivate();
  3168. }
  3169. }
  3170. }
  3171. }
  3172. template<typename Container>
  3173. void SceneComponent::DestroyItems(const Container& entities) const
  3174. {
  3175. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3176. for (auto& entityRef : entities)
  3177. {
  3178. delete entityRef;
  3179. }
  3180. }
  3181. void SceneComponent::DestroyGraphicsItem(const GraphicsEffectId& effectId, QGraphicsItem* graphicsItem)
  3182. {
  3183. if (graphicsItem)
  3184. {
  3185. GraphicsEffectRequestBus::Event(effectId, &GraphicsEffectRequests::OnGraphicsEffectCancelled);
  3186. RemoveItemFromScene(graphicsItem);
  3187. // https://stackoverflow.com/questions/38458830/crash-after-qgraphicssceneremoveitem-with-custom-item-class
  3188. // Scene Index does not correctly update causing a crash when the index tree is queried.
  3189. GraphicsEffectRequestBus::Event(effectId, &GraphicsEffectRequests::PrepareGeometryChange);
  3190. delete graphicsItem;
  3191. }
  3192. // Remove the effect id from our active particle list so we can limit their numbers properly
  3193. AZStd::remove(m_activeParticles.begin(), m_activeParticles.end(), effectId);
  3194. }
  3195. void SceneComponent::InitConnections()
  3196. {
  3197. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3198. BuildEndpointMap(m_graphData);
  3199. InitItems(m_graphData.m_connections);
  3200. }
  3201. void SceneComponent::NotifyConnectedSlots()
  3202. {
  3203. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3204. for (auto& connection : m_graphData.m_connections)
  3205. {
  3206. AZ::Entity* entity = connection;
  3207. auto* connectionEntity = entity ? AZ::EntityUtils::FindFirstDerivedComponent<ConnectionComponent>(entity) : nullptr;
  3208. if (connectionEntity)
  3209. {
  3210. SlotRequestBus::Event(connectionEntity->GetSourceEndpoint().GetSlotId(), &SlotRequests::AddConnectionId, connectionEntity->GetEntityId(), connectionEntity->GetTargetEndpoint());
  3211. SlotRequestBus::Event(connectionEntity->GetTargetEndpoint().GetSlotId(), &SlotRequests::AddConnectionId, connectionEntity->GetEntityId(), connectionEntity->GetSourceEndpoint());
  3212. }
  3213. }
  3214. }
  3215. void SceneComponent::OnSelectionChanged()
  3216. {
  3217. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3218. if((m_isDragSelecting && (m_dragSelectionType != DragSelectionType::Realtime)))
  3219. {
  3220. // Nothing to do.
  3221. return;
  3222. }
  3223. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSelectionChanged);
  3224. }
  3225. void SceneComponent::RegisterSelectionItem(const AZ::EntityId& itemId)
  3226. {
  3227. QGraphicsItem* selectionItem = nullptr;
  3228. SceneMemberUIRequestBus::EventResult(selectionItem, itemId, &SceneMemberUIRequests::GetSelectionItem);
  3229. m_itemLookup[selectionItem] = itemId;
  3230. }
  3231. void SceneComponent::UnregisterSelectionItem(const AZ::EntityId& itemId)
  3232. {
  3233. QGraphicsItem* selectionItem = nullptr;
  3234. SceneMemberUIRequestBus::EventResult(selectionItem, itemId, &SceneMemberUIRequests::GetSelectionItem);
  3235. m_itemLookup.erase(selectionItem);
  3236. m_hiddenElements.erase(selectionItem);
  3237. }
  3238. void SceneComponent::AddSceneMember(const AZ::EntityId& sceneMemberId, bool positionItem, const AZ::Vector2& position)
  3239. {
  3240. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3241. QGraphicsItem* graphicsItem = nullptr;
  3242. SceneMemberUIRequestBus::EventResult(graphicsItem, sceneMemberId, &SceneMemberUIRequests::GetRootGraphicsItem);
  3243. if (graphicsItem)
  3244. {
  3245. if (m_graphicsSceneUi)
  3246. {
  3247. m_graphicsSceneUi->addItem(graphicsItem);
  3248. }
  3249. RegisterSelectionItem(sceneMemberId);
  3250. if (positionItem)
  3251. {
  3252. GeometryRequestBus::Event(sceneMemberId, &GeometryRequests::SetPosition, position);
  3253. }
  3254. SceneMemberRequestBus::Event(sceneMemberId, &SceneMemberRequests::SetScene, GetEntityId());
  3255. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnSceneMemberAdded, sceneMemberId);
  3256. GeometryNotificationBus::MultiHandler::BusConnect(sceneMemberId);
  3257. VisualNotificationBus::MultiHandler::BusConnect(sceneMemberId);
  3258. SceneMemberRequestBus::Event(sceneMemberId, &SceneMemberRequests::SignalMemberSetupComplete);
  3259. }
  3260. }
  3261. void SceneComponent::RemoveItemFromScene(QGraphicsItem* graphicsItem)
  3262. {
  3263. if (graphicsItem)
  3264. {
  3265. if (m_graphicsSceneUi && graphicsItem->scene() == m_graphicsSceneUi.get())
  3266. {
  3267. m_graphicsSceneUi->removeItem(graphicsItem);
  3268. }
  3269. m_hiddenElements.erase(graphicsItem);
  3270. }
  3271. }
  3272. void SceneComponent::SieveSceneMembers(const AZStd::unordered_set<AZ::EntityId>& itemIds, SceneMemberBuckets& sceneMembers) const
  3273. {
  3274. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3275. AZStd::unordered_set< AZ::EntityId > wrapperNodes;
  3276. for (const auto& node : m_graphData.m_nodes)
  3277. {
  3278. if (itemIds.find(node->GetId()) != itemIds.end())
  3279. {
  3280. sceneMembers.m_nodes.insert(node->GetId());
  3281. if (GraphUtils::IsWrapperNode(node->GetId()))
  3282. {
  3283. wrapperNodes.insert(node->GetId());
  3284. }
  3285. }
  3286. }
  3287. // Wrapper nodes handle copying/deleting everything internal to themselves.
  3288. // So we need to sanitize our filtering to avoid things that are wrapped when the wrapper
  3289. // is also copied.
  3290. for (const auto& wrapperNode : wrapperNodes)
  3291. {
  3292. AZStd::vector< AZ::EntityId > wrappedNodes;
  3293. WrapperNodeRequestBus::EventResult(wrappedNodes, wrapperNode, &WrapperNodeRequests::GetWrappedNodeIds);
  3294. for (const auto& wrappedNode : wrappedNodes)
  3295. {
  3296. sceneMembers.m_nodes.erase(wrappedNode);
  3297. }
  3298. }
  3299. for (const auto& connection : m_graphData.m_connections)
  3300. {
  3301. if (itemIds.find(connection->GetId()) != itemIds.end())
  3302. {
  3303. sceneMembers.m_connections.insert(connection->GetId());
  3304. }
  3305. }
  3306. for (const auto& bookmarkAnchors : m_graphData.m_bookmarkAnchors)
  3307. {
  3308. if (itemIds.find(bookmarkAnchors->GetId()) != itemIds.end())
  3309. {
  3310. sceneMembers.m_bookmarkAnchors.insert(bookmarkAnchors->GetId());
  3311. }
  3312. }
  3313. }
  3314. QPointF SceneComponent::GetViewCenterScenePoint() const
  3315. {
  3316. AZ::Vector2 viewCenter(0,0);
  3317. ViewId viewId = GetViewId();
  3318. ViewRequestBus::EventResult(viewCenter, viewId, &ViewRequests::GetViewSceneCenter);
  3319. return QPointF(viewCenter.GetX(), viewCenter.GetY());
  3320. }
  3321. void SceneComponent::OnDragCursorMove(const QPointF& cursorPoint)
  3322. {
  3323. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3324. if (m_enableSpliceTracking)
  3325. {
  3326. AZStd::unordered_set< AZ::EntityId > intersectedEntities;
  3327. AZStd::unordered_map< AZ::EntityId, AZ::EntityId > displayMapping;
  3328. for (auto spliceSource : { m_pressedEntity, m_inputCouplingTarget, m_outputCouplingTarget })
  3329. {
  3330. QGraphicsItem* graphicsItem = nullptr;
  3331. SceneMemberUIRequestBus::EventResult(graphicsItem, spliceSource, &SceneMemberUIRequests::GetRootGraphicsItem);
  3332. if (graphicsItem)
  3333. {
  3334. // We'll use the bounding rect to determine visibility.
  3335. // But we'll use the cursor position to determine snapping
  3336. QRectF boundingRect = graphicsItem->sceneBoundingRect();
  3337. AZStd::vector< AZ::EntityId > sceneEntities = GetEntitiesInRect(boundingRect, Qt::ItemSelectionMode::IntersectsItemShape);
  3338. for (const AZ::EntityId& entityId : sceneEntities)
  3339. {
  3340. if (entityId == spliceSource
  3341. || m_selectedSubGraph.m_containedNodes.find(entityId) != m_selectedSubGraph.m_containedNodes.end()
  3342. || m_selectedSubGraph.m_containedConnections.find(entityId) != m_selectedSubGraph.m_containedConnections.end())
  3343. {
  3344. continue;
  3345. }
  3346. auto insertResult = intersectedEntities.insert(entityId);
  3347. if (insertResult.second)
  3348. {
  3349. displayMapping[entityId] = spliceSource;
  3350. }
  3351. }
  3352. }
  3353. }
  3354. if (!intersectedEntities.empty())
  3355. {
  3356. bool ambiguousNode = false;
  3357. AZ::EntityId hoveredNode;
  3358. AZStd::vector< AZ::EntityId > ambiguousConnections;
  3359. for (const AZ::EntityId& currentEntity : intersectedEntities)
  3360. {
  3361. if (GraphUtils::IsSpliceableConnection(currentEntity)
  3362. && m_selectedSubGraph.m_containedConnections.find(currentEntity) == m_selectedSubGraph.m_containedConnections.end())
  3363. {
  3364. ambiguousConnections.push_back(currentEntity);
  3365. }
  3366. else if (GraphUtils::IsConnectableNode(currentEntity))
  3367. {
  3368. bool isWrapped = false;
  3369. NodeRequestBus::EventResult(isWrapped, currentEntity, &NodeRequests::IsWrapped);
  3370. if (isWrapped)
  3371. {
  3372. AZ::EntityId parentId;
  3373. NodeRequestBus::EventResult(parentId, currentEntity, &NodeRequests::GetWrappingNode);
  3374. while (parentId.IsValid())
  3375. {
  3376. if (parentId == m_inputCouplingTarget
  3377. || parentId == m_outputCouplingTarget)
  3378. {
  3379. break;
  3380. }
  3381. NodeRequestBus::EventResult(isWrapped, currentEntity, &NodeRequests::IsWrapped);
  3382. if (isWrapped)
  3383. {
  3384. NodeRequestBus::EventResult(parentId, parentId, &NodeRequests::GetWrappingNode);
  3385. }
  3386. else
  3387. {
  3388. break;
  3389. }
  3390. }
  3391. if (parentId == m_inputCouplingTarget
  3392. || parentId == m_outputCouplingTarget)
  3393. {
  3394. continue;
  3395. }
  3396. }
  3397. if (hoveredNode.IsValid())
  3398. {
  3399. ambiguousNode = true;
  3400. }
  3401. hoveredNode = currentEntity;
  3402. }
  3403. }
  3404. AZStd::chrono::milliseconds spliceTime(500);
  3405. if (m_enableNodeDragCouplingTracking && !ambiguousNode && hoveredNode.IsValid())
  3406. {
  3407. AZ::EntityId entityTarget = displayMapping[hoveredNode];
  3408. if (entityTarget != m_couplingTarget)
  3409. {
  3410. m_couplingTarget = entityTarget;
  3411. StateController<RootGraphicsItemDisplayState>* stateController = nullptr;
  3412. RootGraphicsItemRequestBus::EventResult(stateController, entityTarget, &RootGraphicsItemRequests::GetDisplayStateStateController);
  3413. m_couplingEntityDisplayStateStateSetter.ResetStateSetter();
  3414. m_couplingEntityDisplayStateStateSetter.AddStateController(stateController);
  3415. }
  3416. InitiateSpliceToNode(hoveredNode);
  3417. AssetEditorSettingsRequestBus::EventResult(spliceTime, GetEditorId(), &AssetEditorSettingsRequests::GetDragCouplingTime);
  3418. }
  3419. else if (m_enableNodeDragConnectionSpliceTracking)
  3420. {
  3421. m_couplingTarget.SetInvalid();
  3422. m_couplingEntityDisplayStateStateSetter.ResetStateSetter();
  3423. InitiateSpliceToConnection(ambiguousConnections);
  3424. AssetEditorSettingsRequestBus::EventResult(spliceTime, GetEditorId(), &AssetEditorSettingsRequests::GetDragConnectionSpliceTime);
  3425. }
  3426. else
  3427. {
  3428. m_spliceTarget.SetInvalid();
  3429. m_couplingTarget.SetInvalid();
  3430. m_couplingEntityDisplayStateStateSetter.ResetStateSetter();
  3431. }
  3432. // If we move, no matter what. Restart the timer, so long as we have a valid target.
  3433. m_spliceTimer.stop();
  3434. if (m_spliceTarget.IsValid())
  3435. {
  3436. m_spliceTimer.setInterval(aznumeric_cast<int>(spliceTime.count()));
  3437. m_spliceTimer.start();
  3438. }
  3439. }
  3440. else
  3441. {
  3442. m_spliceTarget.SetInvalid();
  3443. m_couplingTarget.SetInvalid();
  3444. m_couplingEntityDisplayStateStateSetter.ResetStateSetter();
  3445. m_spliceTargetDisplayStateStateSetter.ResetStateSetter();
  3446. m_pressedEntityDisplayStateStateSetter.ReleaseState();
  3447. m_spliceTimer.stop();
  3448. }
  3449. }
  3450. if (!m_draggedGroupableElements.empty())
  3451. {
  3452. DetermineDragGroupTarget(cursorPoint);
  3453. }
  3454. }
  3455. void SceneComponent::DetermineDragGroupTarget(const QPointF& cursorPoint)
  3456. {
  3457. AZ::EntityId bestGroup = FindGroupTarget(cursorPoint, m_ignoredDragTargets);
  3458. if (bestGroup != m_dragTargetGroup)
  3459. {
  3460. m_dragTargetGroup = bestGroup;
  3461. m_forcedGroupDisplayStateStateSetter.ResetStateSetter();
  3462. if (m_dragTargetGroup.IsValid())
  3463. {
  3464. StateController<RootGraphicsItemDisplayState>* displayStateController = nullptr;
  3465. RootGraphicsItemRequestBus::EventResult(displayStateController, m_dragTargetGroup, &RootGraphicsItemRequests::GetDisplayStateStateController);
  3466. m_forcedGroupDisplayStateStateSetter.AddStateController(displayStateController);
  3467. m_forcedGroupDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::Inspection);
  3468. StateController<AZStd::string>* layerStateController = nullptr;
  3469. LayerControllerRequestBus::EventResult(layerStateController, m_dragTargetGroup, &LayerControllerRequests::GetLayerModifierController);
  3470. m_forcedLayerStateSetter.AddStateController(layerStateController);
  3471. m_forcedLayerStateSetter.SetState("dropTarget");
  3472. }
  3473. }
  3474. }
  3475. AZ::EntityId SceneComponent::FindGroupTarget(const QPointF& scenePoint, const AZStd::unordered_set<AZ::EntityId>& ignoreElements)
  3476. {
  3477. auto entitiesAtPoint = GetEntitiesAt(ConversionUtils::QPointToVector(scenePoint));
  3478. AZStd::unordered_set< AZ::EntityId > groupParentChain;
  3479. AZ::EntityId bestGroup;
  3480. for (auto testEntity : entitiesAtPoint)
  3481. {
  3482. if (ignoreElements.find(testEntity) != ignoreElements.end())
  3483. {
  3484. continue;
  3485. }
  3486. // Only care about groups here. Can ignore anything else for this.
  3487. if (GraphUtils::IsNodeGroup(testEntity))
  3488. {
  3489. bool allowGroup = true;
  3490. // Safe guard against trying to drag a parent group into a child and creating an infinite loop.
  3491. AZStd::unordered_set<AZ::EntityId> testParentChain;
  3492. AZ::EntityId groupedId = testEntity;
  3493. while (groupedId.IsValid())
  3494. {
  3495. GroupableSceneMemberRequests* groupableRequests = GroupableSceneMemberRequestBus::FindFirstHandler(groupedId);
  3496. if (groupableRequests)
  3497. {
  3498. if (ignoreElements.find(groupedId) != ignoreElements.end())
  3499. {
  3500. allowGroup = false;
  3501. break;
  3502. }
  3503. if (GraphUtils::IsNodeGroup(groupedId))
  3504. {
  3505. testParentChain.insert(groupedId);
  3506. }
  3507. groupedId = groupableRequests->GetGroupId();
  3508. }
  3509. else
  3510. {
  3511. break;
  3512. }
  3513. }
  3514. if (!allowGroup)
  3515. {
  3516. continue;
  3517. }
  3518. ////
  3519. if (bestGroup.IsValid())
  3520. {
  3521. // If this group is apart of the previous chain, we can ignore it as we have the more specific group.
  3522. if (groupParentChain.find(testEntity) == groupParentChain.end())
  3523. {
  3524. AZ::EntityId groupedId2 = testEntity;
  3525. for (AZ::EntityId testParent : testParentChain)
  3526. {
  3527. if (GraphUtils::IsNodeGroup(testParent))
  3528. {
  3529. testParentChain.insert(testParent);
  3530. }
  3531. // If we discover a more specific version. We can update to that.
  3532. if (groupedId2 == bestGroup)
  3533. {
  3534. bestGroup = testEntity;
  3535. groupParentChain = testParentChain;
  3536. break;
  3537. }
  3538. }
  3539. // If we have two equally 'valid' groups then we want to just ignore them both as the drop is ambiguous.
  3540. if (bestGroup != testEntity)
  3541. {
  3542. bestGroup.SetInvalid();
  3543. break;
  3544. }
  3545. }
  3546. }
  3547. else
  3548. {
  3549. bestGroup = testEntity;
  3550. groupParentChain = testParentChain;
  3551. }
  3552. }
  3553. }
  3554. return bestGroup;
  3555. }
  3556. void SceneComponent::OnTrySplice()
  3557. {
  3558. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3559. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPushPreventUndoStateUpdate);
  3560. m_spliceTargetDisplayStateStateSetter.ResetStateSetter();
  3561. m_pressedEntityDisplayStateStateSetter.ReleaseState();
  3562. m_couplingEntityDisplayStateStateSetter.ReleaseState();
  3563. // Make sure we have a valid target for whatever we are trying to 'splice' against.
  3564. // Then check the preconditions for the various other tracking elements.
  3565. if (m_enableSpliceTracking && m_spliceTarget.IsValid()
  3566. && ( (m_enableNodeDragCouplingTracking && (m_inputCouplingTarget.IsValid() || m_outputCouplingTarget.IsValid()))
  3567. || (m_enableNodeDragConnectionSpliceTracking && m_pressedEntity.IsValid())
  3568. || (m_enableNodeChainDragConnectionSpliceTracking && !m_selectedSubGraph.m_containedNodes.empty())
  3569. )
  3570. )
  3571. {
  3572. AnimatedPulseConfiguration pulseConfiguration;
  3573. pulseConfiguration.m_durationSec = 0.35f;
  3574. pulseConfiguration.m_enableGradient = true;
  3575. AZ::EntityId pulseTarget = m_pressedEntity;
  3576. if (GraphUtils::IsConnection(m_spliceTarget))
  3577. {
  3578. if (m_enableNodeChainDragConnectionSpliceTracking)
  3579. {
  3580. if (GraphUtils::SpliceSubGraphOntoConnection(m_selectedSubGraph, m_spliceTarget))
  3581. {
  3582. m_forceDragReleaseUndo = true;
  3583. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  3584. StartNudging(m_selectedSubGraph.m_containedNodes);
  3585. }
  3586. else
  3587. {
  3588. pulseConfiguration.m_drawColor = QColor(255, 0, 0);
  3589. }
  3590. }
  3591. else
  3592. {
  3593. ConnectionSpliceConfig spliceConfig;
  3594. spliceConfig.m_allowOpportunisticConnections = false;
  3595. if (GraphUtils::SpliceNodeOntoConnection(m_pressedEntity, m_spliceTarget, spliceConfig))
  3596. {
  3597. m_forceDragReleaseUndo = true;
  3598. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  3599. StartNudging(m_selectedSubGraph.m_containedNodes);
  3600. }
  3601. else
  3602. {
  3603. pulseConfiguration.m_drawColor = QColor(255, 0, 0);
  3604. }
  3605. }
  3606. }
  3607. else if (GraphUtils::IsNode(m_spliceTarget))
  3608. {
  3609. pulseTarget = m_couplingTarget;
  3610. QRectF targetRect;
  3611. QGraphicsItem* targetItem = nullptr;
  3612. SceneMemberUIRequestBus::EventResult(targetItem, m_spliceTarget, &SceneMemberUIRequests::GetRootGraphicsItem);
  3613. if (targetItem)
  3614. {
  3615. targetRect = targetItem->sceneBoundingRect();
  3616. }
  3617. QGraphicsItem* draggingEntity = nullptr;
  3618. AZStd::unordered_set< GraphCanvas::ConnectionType > allowableTypes;
  3619. if (m_inputCouplingTarget == m_outputCouplingTarget)
  3620. {
  3621. allowableTypes.insert(GraphCanvas::ConnectionType::CT_Input);
  3622. allowableTypes.insert(GraphCanvas::ConnectionType::CT_Output);
  3623. SceneMemberUIRequestBus::EventResult(draggingEntity, m_inputCouplingTarget, &SceneMemberUIRequests::GetRootGraphicsItem);
  3624. }
  3625. else if (m_couplingTarget == m_inputCouplingTarget)
  3626. {
  3627. allowableTypes.insert(GraphCanvas::ConnectionType::CT_Input);
  3628. }
  3629. else
  3630. {
  3631. allowableTypes.insert(GraphCanvas::ConnectionType::CT_Output);
  3632. }
  3633. SceneMemberUIRequestBus::EventResult(draggingEntity, m_couplingTarget, &SceneMemberUIRequests::GetRootGraphicsItem);
  3634. if (draggingEntity && targetItem)
  3635. {
  3636. QRectF draggingRect = draggingEntity->sceneBoundingRect();
  3637. GraphCanvas::ConnectionType allowedType = GraphCanvas::ConnectionType::CT_None;
  3638. // Reference point is we are gathering slots from the pressed node.
  3639. // So we want to determine which side is offset from, and grabs the nodes from the other side.
  3640. if (draggingRect.x() > targetRect.x())
  3641. {
  3642. allowedType = GraphCanvas::ConnectionType::CT_Input;
  3643. }
  3644. else
  3645. {
  3646. allowedType = GraphCanvas::ConnectionType::CT_Output;
  3647. }
  3648. AZStd::vector< Endpoint > connectableEndpoints;
  3649. if (allowableTypes.count(allowedType) > 0)
  3650. {
  3651. AZStd::vector< AZ::EntityId > slotIds;
  3652. NodeRequestBus::EventResult(slotIds, m_couplingTarget, &NodeRequests::GetSlotIds);
  3653. for (const AZ::EntityId& testSlotId : slotIds)
  3654. {
  3655. if (GraphUtils::IsSlotVisible(testSlotId))
  3656. {
  3657. GraphCanvas::ConnectionType connectionType = GraphCanvas::ConnectionType::CT_Invalid;
  3658. SlotRequestBus::EventResult(connectionType, testSlotId, &SlotRequests::GetConnectionType);
  3659. if (connectionType == allowedType)
  3660. {
  3661. connectableEndpoints.emplace_back(m_couplingTarget, testSlotId);
  3662. }
  3663. }
  3664. }
  3665. }
  3666. CreateConnectionsBetweenConfig config;
  3667. config.m_connectionType = CreateConnectionsBetweenConfig::CreationType::SinglePass;
  3668. if (!connectableEndpoints.empty() && GraphUtils::CreateConnectionsBetween(connectableEndpoints, m_spliceTarget, config))
  3669. {
  3670. m_forceDragReleaseUndo = true;
  3671. pulseConfiguration.m_drawColor = QColor(255, 255, 255);
  3672. }
  3673. else
  3674. {
  3675. pulseConfiguration.m_drawColor = QColor(255, 0, 0);
  3676. }
  3677. }
  3678. }
  3679. QGraphicsItem* item = nullptr;
  3680. SceneMemberUIRequestBus::EventResult(item, pulseTarget, &SceneMemberUIRequests::GetRootGraphicsItem);
  3681. if (item)
  3682. {
  3683. pulseConfiguration.m_zValue = item->zValue() - 1;
  3684. }
  3685. CreatePulseAroundSceneMember(pulseTarget, 3, pulseConfiguration);
  3686. m_spliceTarget.SetInvalid();
  3687. }
  3688. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPopPreventUndoStateUpdate);
  3689. }
  3690. void SceneComponent::InitiateSpliceToNode(const NodeId& nodeId)
  3691. {
  3692. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3693. if (m_spliceTarget != nodeId)
  3694. {
  3695. m_spliceTargetDisplayStateStateSetter.ResetStateSetter();
  3696. m_spliceTarget = nodeId;
  3697. if (m_spliceTarget.IsValid())
  3698. {
  3699. m_couplingEntityDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::InspectionTransparent);
  3700. StateController<RootGraphicsItemDisplayState>* stateController;
  3701. RootGraphicsItemRequestBus::EventResult(stateController, m_spliceTarget, &RootGraphicsItemRequests::GetDisplayStateStateController);
  3702. m_spliceTargetDisplayStateStateSetter.AddStateController(stateController);
  3703. m_spliceTargetDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::Preview);
  3704. }
  3705. else
  3706. {
  3707. m_couplingEntityDisplayStateStateSetter.ReleaseState();
  3708. }
  3709. }
  3710. }
  3711. void SceneComponent::InitiateSpliceToConnection(const AZStd::vector<ConnectionId>& connectionIds)
  3712. {
  3713. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3714. m_spliceTarget.SetInvalid();
  3715. m_spliceTargetDisplayStateStateSetter.ResetStateSetter();
  3716. if (!connectionIds.empty())
  3717. {
  3718. m_pressedEntityDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::InspectionTransparent);
  3719. }
  3720. else if (m_pressedEntityDisplayStateStateSetter.HasState())
  3721. {
  3722. m_pressedEntityDisplayStateStateSetter.ReleaseState();
  3723. }
  3724. GraphCanvasGraphicsView* graphicsView = nullptr;
  3725. ViewRequestBus::EventResult(graphicsView, m_viewId, &ViewRequests::AsGraphicsView);
  3726. QPointF scenePoint;
  3727. if (graphicsView)
  3728. {
  3729. QPointF cursorPoint = QCursor::pos();
  3730. QPointF viewPoint = graphicsView->mapFromGlobal(cursorPoint.toPoint());
  3731. scenePoint = graphicsView->mapToScene(viewPoint.toPoint());
  3732. }
  3733. for (const ConnectionId& connectionId : connectionIds)
  3734. {
  3735. bool containsCursor = false;
  3736. QGraphicsItem* spliceTargetItem = nullptr;
  3737. SceneMemberUIRequestBus::EventResult(spliceTargetItem, connectionId, &SceneMemberUIRequests::GetRootGraphicsItem);
  3738. if (spliceTargetItem)
  3739. {
  3740. containsCursor = spliceTargetItem->contains(scenePoint);
  3741. }
  3742. if (containsCursor)
  3743. {
  3744. m_spliceTarget = connectionId;
  3745. StateController<RootGraphicsItemDisplayState>* stateController;
  3746. RootGraphicsItemRequestBus::EventResult(stateController, m_spliceTarget, &RootGraphicsItemRequests::GetDisplayStateStateController);
  3747. m_spliceTargetDisplayStateStateSetter.AddStateController(stateController);
  3748. m_spliceTargetDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::Preview);
  3749. }
  3750. }
  3751. }
  3752. //////////////////////////////
  3753. // GraphCanvasGraphicsScenes
  3754. //////////////////////////////
  3755. GraphCanvasGraphicsScene::GraphCanvasGraphicsScene(SceneComponent& scene)
  3756. : m_scene(scene)
  3757. , m_suppressContextMenu(false)
  3758. {
  3759. setMinimumRenderSize(2.0f);
  3760. connect(this, &QGraphicsScene::selectionChanged, this, [this]() { m_scene.OnSelectionChanged(); });
  3761. setSceneRect(-20000, -20000, 40000, 40000);
  3762. }
  3763. AZ::EntityId GraphCanvasGraphicsScene::GetEntityId() const
  3764. {
  3765. return m_scene.GetEntityId();
  3766. }
  3767. void GraphCanvasGraphicsScene::SuppressNextContextMenu()
  3768. {
  3769. m_suppressContextMenu = true;
  3770. }
  3771. void GraphCanvasGraphicsScene::keyPressEvent(QKeyEvent* event)
  3772. {
  3773. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnKeyPressed, event);
  3774. QGraphicsScene::keyPressEvent(event);
  3775. }
  3776. void GraphCanvasGraphicsScene::keyReleaseEvent(QKeyEvent* event)
  3777. {
  3778. SceneNotificationBus::Event(GetEntityId(), &SceneNotifications::OnKeyReleased, event);
  3779. QGraphicsScene::keyPressEvent(event);
  3780. }
  3781. void GraphCanvasGraphicsScene::contextMenuEvent(QGraphicsSceneContextMenuEvent* contextMenuEvent)
  3782. {
  3783. if (!m_suppressContextMenu && m_scene.AllowContextMenu())
  3784. {
  3785. const QPoint& screenPos = contextMenuEvent->screenPos();
  3786. const QPointF& scenePos = contextMenuEvent->scenePos();
  3787. contextMenuEvent->ignore();
  3788. ContextMenuAction::SceneReaction reaction = ContextMenuAction::SceneReaction::Unknown;
  3789. // Send the event to all items at this position until one item accepts the event.
  3790. for (QGraphicsItem* item : itemsAtPosition(contextMenuEvent->screenPos(), contextMenuEvent->scenePos(), contextMenuEvent->widget()))
  3791. {
  3792. AZ::EntityId memberId;
  3793. auto mapIter = m_scene.m_itemLookup.find(item);
  3794. if (mapIter != m_scene.m_itemLookup.end())
  3795. {
  3796. memberId = mapIter->second;
  3797. }
  3798. if (!memberId.IsValid())
  3799. {
  3800. continue;
  3801. }
  3802. else if (memberId == m_scene.GetGrid())
  3803. {
  3804. // Scene context menu might add elements to the scene. So we'll want to highlight the group to ensure we communicate
  3805. // that the group will be affected by these adds.
  3806. m_contextMenuGroupTarget = m_scene.FindGroupTarget(scenePos);
  3807. SignalGroupHighlight();
  3808. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowSceneContextMenuWithGroup, screenPos, scenePos, m_contextMenuGroupTarget);
  3809. }
  3810. else
  3811. {
  3812. // Want to early out before I do the selection manipulation for the node groups.
  3813. // unless it's in the title. Then I treat it like normal.
  3814. if (GraphUtils::IsNodeGroup(memberId))
  3815. {
  3816. bool isInTitle = false;
  3817. NodeGroupRequestBus::EventResult(isInTitle, memberId, &NodeGroupRequests::IsInTitle, scenePos);
  3818. if (!isInTitle)
  3819. {
  3820. continue;
  3821. }
  3822. }
  3823. bool isMemberSelected = false;
  3824. SceneMemberUIRequestBus::EventResult(isMemberSelected, memberId, &SceneMemberUIRequests::IsSelected);
  3825. bool shouldAppendSelection = contextMenuEvent->modifiers().testFlag(Qt::ControlModifier);
  3826. // clear the current selection if you are not multi selecting and clicking on an unselected node
  3827. if (!isMemberSelected && !shouldAppendSelection)
  3828. {
  3829. m_scene.ClearSelection();
  3830. }
  3831. if (!isMemberSelected)
  3832. {
  3833. SceneMemberUIRequestBus::Event(memberId, &SceneMemberUIRequests::SetSelected, true);
  3834. }
  3835. contextMenuEvent->accept();
  3836. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPushPreventUndoStateUpdate);
  3837. if (GraphUtils::IsNodeGroup(memberId))
  3838. {
  3839. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowNodeGroupContextMenu, memberId, screenPos, scenePos);
  3840. }
  3841. else if (GraphUtils::IsConnection(memberId))
  3842. {
  3843. // Connection Context Menu might add elements to the scene. So we'll want to highlight the group to ensure we communicate
  3844. // that the group will be affected by these adds.
  3845. m_contextMenuGroupTarget = m_scene.FindGroupTarget(scenePos);
  3846. SignalGroupHighlight();
  3847. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowConnectionContextMenuWithGroup, memberId, screenPos, scenePos, m_contextMenuGroupTarget);
  3848. }
  3849. else if (GraphUtils::IsBookmarkAnchor(memberId))
  3850. {
  3851. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowBookmarkContextMenu, memberId, screenPos, scenePos);
  3852. }
  3853. else if (GraphUtils::IsComment(memberId))
  3854. {
  3855. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowCommentContextMenu, memberId, screenPos, scenePos);
  3856. }
  3857. else
  3858. {
  3859. bool isNode = GraphUtils::IsNode(memberId);
  3860. bool isCollapsedGroup = GraphUtils::IsCollapsedNodeGroup(memberId);
  3861. if (GraphUtils::IsNode(memberId))
  3862. {
  3863. AZStd::vector< SlotId > slotIds;
  3864. NodeRequestBus::EventResult(slotIds, memberId, &NodeRequests::GetSlotIds);
  3865. AZ::Vector2 azScenePoint = ConversionUtils::QPointToVector(scenePos);
  3866. SlotId targetSlotId;
  3867. for (const SlotId& slotId : slotIds)
  3868. {
  3869. bool isSlotContextMenu = false;
  3870. VisualRequestBus::EventResult(isSlotContextMenu, slotId, &VisualRequests::Contains, azScenePoint);
  3871. if (isSlotContextMenu)
  3872. {
  3873. if (GraphUtils::IsSlotVisible(slotId))
  3874. {
  3875. targetSlotId = slotId;
  3876. break;
  3877. }
  3878. }
  3879. }
  3880. if (targetSlotId.IsValid())
  3881. {
  3882. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowSlotContextMenu, targetSlotId, screenPos, scenePos);
  3883. }
  3884. }
  3885. if (reaction == ContextMenuAction::SceneReaction::Unknown)
  3886. {
  3887. if (GraphUtils::IsComment(memberId)
  3888. || isNode)
  3889. {
  3890. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowNodeContextMenu, memberId, screenPos, scenePos);
  3891. }
  3892. else if (isCollapsedGroup)
  3893. {
  3894. AssetEditorRequestBus::EventResult(reaction, m_scene.GetEditorId(), &AssetEditorRequests::ShowCollapsedNodeGroupContextMenu, memberId, screenPos, scenePos);
  3895. }
  3896. }
  3897. }
  3898. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestPopPreventUndoStateUpdate);
  3899. }
  3900. break;
  3901. }
  3902. if (reaction == ContextMenuAction::SceneReaction::PostUndo)
  3903. {
  3904. GraphModelRequestBus::Event(GetEntityId(), &GraphModelRequests::RequestUndoPoint);
  3905. }
  3906. }
  3907. else
  3908. {
  3909. m_suppressContextMenu = false;
  3910. }
  3911. CleanupHighlight();
  3912. }
  3913. QList<QGraphicsItem*> GraphCanvasGraphicsScene::itemsAtPosition(const QPoint& screenPos, const QPointF& scenePos, QWidget* widget) const
  3914. {
  3915. GRAPH_CANVAS_DETAILED_PROFILE_FUNCTION();
  3916. QGraphicsView* view = widget ? qobject_cast<QGraphicsView*>(widget->parentWidget()) : nullptr;
  3917. if (!view)
  3918. {
  3919. return items(scenePos, Qt::IntersectsItemShape, Qt::DescendingOrder, QTransform());
  3920. }
  3921. const QRectF pointRect(QPointF(widget->mapFromGlobal(screenPos)), QSizeF(1, 1));
  3922. if (!view->isTransformed())
  3923. {
  3924. return items(pointRect, Qt::IntersectsItemShape, Qt::DescendingOrder);
  3925. }
  3926. const QTransform viewTransform = view->viewportTransform();
  3927. if (viewTransform.type() <= QTransform::TxScale)
  3928. {
  3929. return items(viewTransform.inverted().mapRect(pointRect), Qt::IntersectsItemShape,
  3930. Qt::DescendingOrder, viewTransform);
  3931. }
  3932. return items(viewTransform.inverted().map(pointRect), Qt::IntersectsItemShape,
  3933. Qt::DescendingOrder, viewTransform);
  3934. }
  3935. void GraphCanvasGraphicsScene::mousePressEvent(QGraphicsSceneMouseEvent* event)
  3936. {
  3937. if (event->button() == Qt::RightButton)
  3938. {
  3939. // IMPORTANT: When the user right-clicks on the scene,
  3940. // and there are NO items at the click position, the
  3941. // current selection is lost. See documentation:
  3942. //
  3943. // "If there is no item at the given position on the scene,
  3944. // the selection area is reset, any focus item loses its
  3945. // input focus, and the event is then ignored."
  3946. // http://doc.qt.io/qt-5/qgraphicsscene.html#mousePressEvent
  3947. //
  3948. // This ISN'T the behavior we want. We want to preserve
  3949. // the current selection to allow scene interactions. To get around
  3950. // this behavior, we'll accept the event and by-pass its
  3951. // default implementation.
  3952. event->accept();
  3953. return;
  3954. }
  3955. QGraphicsScene::mousePressEvent(event);
  3956. }
  3957. void GraphCanvasGraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)
  3958. {
  3959. m_scene.OnSelectionChanged();
  3960. QGraphicsScene::mouseReleaseEvent(event);
  3961. m_scene.FinalizeNudging();
  3962. }
  3963. void GraphCanvasGraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
  3964. {
  3965. QPointF scenePos = event->scenePos();
  3966. QPointF lastScenePos = event->lastScenePos();
  3967. // These events seem to fire off regardless of mouse input(so long as mouse is down) which causes weird behavior(broken ctrl+left selection).
  3968. // Only process these if there was actual movement.
  3969. if (scenePos == lastScenePos)
  3970. {
  3971. return;
  3972. }
  3973. QGraphicsScene::mouseMoveEvent(event);
  3974. if ((m_scene.m_enableSpliceTracking || m_scene.m_isDraggingEntity) && event->lastPos() != event->pos())
  3975. {
  3976. m_scene.OnDragCursorMove(scenePos);
  3977. }
  3978. }
  3979. void GraphCanvasGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent * event)
  3980. {
  3981. QGraphicsScene::dragEnterEvent(event);
  3982. m_scene.OnSceneDragEnter(event->mimeData());
  3983. if (m_scene.HasActiveMimeDelegates())
  3984. {
  3985. event->accept();
  3986. event->acceptProposedAction();
  3987. }
  3988. }
  3989. void GraphCanvasGraphicsScene::dragLeaveEvent(QGraphicsSceneDragDropEvent* event)
  3990. {
  3991. QGraphicsScene::dragLeaveEvent(event);
  3992. m_scene.OnSceneDragExit(event->mimeData());
  3993. }
  3994. void GraphCanvasGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent* event)
  3995. {
  3996. QGraphicsScene::dragMoveEvent(event);
  3997. m_scene.OnSceneDragMoveEvent(event->scenePos(), event->mimeData());
  3998. if (m_scene.HasActiveMimeDelegates())
  3999. {
  4000. event->accept();
  4001. event->acceptProposedAction();
  4002. }
  4003. }
  4004. void GraphCanvasGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent* event)
  4005. {
  4006. bool accepted = event->isAccepted();
  4007. event->setAccepted(false);
  4008. QGraphicsScene::dropEvent(event);
  4009. if (!event->isAccepted() && m_scene.HasActiveMimeDelegates())
  4010. {
  4011. event->accept();
  4012. m_scene.OnSceneDropEvent(event->scenePos(), event->mimeData());
  4013. }
  4014. else
  4015. {
  4016. event->setAccepted(accepted);
  4017. }
  4018. }
  4019. void GraphCanvasGraphicsScene::SignalGroupHighlight()
  4020. {
  4021. if (m_contextMenuGroupTarget.IsValid())
  4022. {
  4023. StateController<RootGraphicsItemDisplayState>* displayStateController = nullptr;
  4024. RootGraphicsItemRequestBus::EventResult(displayStateController, m_contextMenuGroupTarget, &RootGraphicsItemRequests::GetDisplayStateStateController);
  4025. m_forcedGroupDisplayStateStateSetter.AddStateController(displayStateController);
  4026. m_forcedGroupDisplayStateStateSetter.SetState(RootGraphicsItemDisplayState::Inspection);
  4027. StateController<AZStd::string>* layerStateController = nullptr;
  4028. LayerControllerRequestBus::EventResult(layerStateController, m_contextMenuGroupTarget, &LayerControllerRequests::GetLayerModifierController);
  4029. m_forcedLayerStateSetter.AddStateController(layerStateController);
  4030. m_forcedLayerStateSetter.SetState("dropTarget");
  4031. }
  4032. }
  4033. void GraphCanvasGraphicsScene::CleanupHighlight()
  4034. {
  4035. m_contextMenuGroupTarget.SetInvalid();
  4036. m_forcedGroupDisplayStateStateSetter.ResetStateSetter();
  4037. m_forcedLayerStateSetter.ResetStateSetter();
  4038. }
  4039. }