CryEdit.cpp 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519
  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 "EditorDefs.h"
  9. #ifdef WIN32
  10. AZ_PUSH_DISABLE_WARNING(4458, "-Wunknown-warning-option")
  11. #include <gdiplus.h>
  12. AZ_POP_DISABLE_WARNING
  13. #pragma comment (lib, "Gdiplus.lib")
  14. #include <WinUser.h> // needed for MessageBoxW in the assert handler
  15. #endif
  16. #include <array>
  17. #include <string>
  18. #include <iostream>
  19. #include <fstream>
  20. #include "CryEdit.h"
  21. // Qt
  22. #include <QCommandLineParser>
  23. #include <QSharedMemory>
  24. #include <QSystemSemaphore>
  25. #include <QDesktopServices>
  26. #include <QElapsedTimer>
  27. #include <QProcess>
  28. #include <QScopedValueRollback>
  29. #include <QClipboard>
  30. #include <QMenuBar>
  31. #include <QMessageBox>
  32. #include <QDialogButtonBox>
  33. #include <QUrlQuery>
  34. // AzCore
  35. #include <AzCore/Casting/numeric_cast.h>
  36. #include <AzCore/Component/ComponentApplicationBus.h>
  37. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  38. #include <AzCore/Module/Environment.h>
  39. #include <AzCore/RTTI/BehaviorContext.h>
  40. #include <AzCore/std/smart_ptr/make_shared.h>
  41. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  42. #include <AzCore/StringFunc/StringFunc.h>
  43. #include <AzCore/Utils/Utils.h>
  44. #include <AzCore/Console/IConsole.h>
  45. #include <AzCore/EBus/IEventScheduler.h>
  46. #include <AzCore/Name/Name.h>
  47. #include <AzCore/IO/SystemFile.h>
  48. // AzFramework
  49. #include <AzFramework/Components/CameraBus.h>
  50. #include <AzFramework/Process/ProcessWatcher.h>
  51. #include <AzFramework/ProjectManager/ProjectManager.h>
  52. #include <AzFramework/Spawnable/RootSpawnableInterface.h>
  53. // AzToolsFramework
  54. #include <AzToolsFramework/ActionManager/ActionManagerSystemComponent.h>
  55. #include <AzToolsFramework/Component/EditorComponentAPIBus.h>
  56. #include <AzToolsFramework/Component/EditorLevelComponentAPIBus.h>
  57. #include <AzToolsFramework/Editor/ActionManagerUtils.h>
  58. #include <AzToolsFramework/UI/UICore/ProgressShield.hxx>
  59. #include <AzToolsFramework/UI/UICore/WidgetHelpers.h>
  60. #include <AzToolsFramework/ViewportSelection/EditorTransformComponentSelectionRequestBus.h>
  61. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  62. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  63. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  64. #include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
  65. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  66. #include <AzToolsFramework/Viewport/LocalViewBookmarkLoader.h>
  67. // AzQtComponents
  68. #include <AzQtComponents/Components/StyleManager.h>
  69. #include <AzQtComponents/Utilities/HandleDpiAwareness.h>
  70. #include <AzQtComponents/Components/WindowDecorationWrapper.h>
  71. #include <AzQtComponents/Utilities/QtPluginPaths.h>
  72. // CryCommon
  73. #include <CryCommon/ILevelSystem.h>
  74. // Editor
  75. #include "Settings.h"
  76. #include "GameResourcesExporter.h"
  77. #include "MainWindow.h"
  78. #include "Core/QtEditorApplication.h"
  79. #include "NewLevelDialog.h"
  80. #include "LayoutConfigDialog.h"
  81. #include "ViewManager.h"
  82. #include "FileTypeUtils.h"
  83. #include "PluginManager.h"
  84. #include "IEditorImpl.h"
  85. #include "StartupLogoDialog.h"
  86. #include "DisplaySettings.h"
  87. #include "GameEngine.h"
  88. #include "StartupTraceHandler.h"
  89. #include "ToolsConfigPage.h"
  90. #include "WaitProgress.h"
  91. #include "ToolBox.h"
  92. #include "EditorPreferencesDialog.h"
  93. #include "AnimationContext.h"
  94. #include "GotoPositionDlg.h"
  95. #include "ConsoleDialog.h"
  96. #include "Controls/ConsoleSCB.h"
  97. #include "ScopedVariableSetter.h"
  98. #include "Util/3DConnexionDriver.h"
  99. #include "Util/AutoDirectoryRestoreFileDialog.h"
  100. #include "Util/EditorAutoLevelLoadTest.h"
  101. #include <AzToolsFramework/PythonTerminal/ScriptHelpDialog.h>
  102. #include "LevelFileDialog.h"
  103. #include "LevelIndependentFileMan.h"
  104. #include "WelcomeScreen/WelcomeScreenDialog.h"
  105. #include "Controls/ReflectedPropertyControl/PropertyCtrl.h"
  106. #include "Controls/ReflectedPropertyControl/ReflectedVar.h"
  107. #include "EditorToolsApplication.h"
  108. #include <AzToolsFramework/Undo/UndoSystem.h>
  109. #if defined(AZ_PLATFORM_WINDOWS)
  110. #include <AzFramework/API/ApplicationAPI_Platform.h>
  111. #endif
  112. #if AZ_TRAIT_OS_PLATFORM_APPLE
  113. #include "WindowObserver_mac.h"
  114. #endif
  115. #include <AzCore/RTTI/BehaviorContext.h>
  116. #include <AzFramework/Render/Intersector.h>
  117. #include <AzCore/std/smart_ptr/make_shared.h>
  118. static const char O3DEEditorClassName[] = "O3DEEditorClass";
  119. static const char O3DEApplicationName[] = "O3DEApplication";
  120. static AZ::EnvironmentVariable<bool> inEditorBatchMode = nullptr;
  121. namespace Platform
  122. {
  123. bool OpenUri(const QUrl& uri);
  124. }
  125. RecentFileList::RecentFileList()
  126. {
  127. m_settings.beginGroup(QStringLiteral("Application"));
  128. m_settings.beginGroup(QStringLiteral("Recent File List"));
  129. ReadList();
  130. }
  131. void RecentFileList::Remove(int index)
  132. {
  133. m_arrNames.removeAt(index);
  134. }
  135. void RecentFileList::Add(const QString& f)
  136. {
  137. QString filename = QDir::toNativeSeparators(f);
  138. m_arrNames.removeAll(filename);
  139. m_arrNames.push_front(filename);
  140. while (m_arrNames.count() > Max)
  141. {
  142. m_arrNames.removeAt(Max);
  143. }
  144. }
  145. int RecentFileList::GetSize()
  146. {
  147. return m_arrNames.count();
  148. }
  149. void RecentFileList::GetDisplayName(QString& name, int index, const QString& curDir)
  150. {
  151. name = m_arrNames[index];
  152. const QDir cur(curDir);
  153. QDir fileDir(name); // actually pointing at file, first cdUp() gets us the parent dir
  154. while (fileDir.cdUp())
  155. {
  156. if (fileDir == cur)
  157. {
  158. name = cur.relativeFilePath(name);
  159. break;
  160. }
  161. }
  162. name = QDir::toNativeSeparators(name);
  163. }
  164. QString& RecentFileList::operator[](int index)
  165. {
  166. return m_arrNames[index];
  167. }
  168. void RecentFileList::ReadList()
  169. {
  170. m_arrNames.clear();
  171. for (int i = 1; i <= Max; ++i)
  172. {
  173. QString f = m_settings.value(QStringLiteral("File%1").arg(i)).toString();
  174. if (!f.isEmpty())
  175. {
  176. m_arrNames.push_back(f);
  177. }
  178. }
  179. }
  180. void RecentFileList::WriteList()
  181. {
  182. m_settings.remove(QString());
  183. int i = 1;
  184. for (auto f : m_arrNames)
  185. {
  186. m_settings.setValue(QStringLiteral("File%1").arg(i++), f);
  187. }
  188. }
  189. #define ERROR_LEN 256
  190. CCryDocManager::CCryDocManager()
  191. {
  192. }
  193. CCrySingleDocTemplate* CCryDocManager::SetDefaultTemplate(CCrySingleDocTemplate* pNew)
  194. {
  195. CCrySingleDocTemplate* pOld = m_pDefTemplate;
  196. m_pDefTemplate = pNew;
  197. m_templateList.clear();
  198. m_templateList.push_back(m_pDefTemplate);
  199. return pOld;
  200. }
  201. // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog
  202. void CCryDocManager::OnFileNew()
  203. {
  204. assert(m_pDefTemplate != nullptr);
  205. m_pDefTemplate->OpenDocumentFile(nullptr);
  206. // if returns NULL, the user has already been alerted
  207. }
  208. bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle,
  209. [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate)
  210. {
  211. CLevelFileDialog levelFileDialog(bOpenFileDialog);
  212. levelFileDialog.show();
  213. levelFileDialog.adjustSize();
  214. if (levelFileDialog.exec() == QDialog::Accepted)
  215. {
  216. fileName = levelFileDialog.GetFileName();
  217. return true;
  218. }
  219. return false;
  220. }
  221. CCryEditDoc* CCryDocManager::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  222. {
  223. assert(filename != nullptr);
  224. const bool reopenIfSame = openSameLevelOptions == COpenSameLevelOptions::ReopenLevelIfSame;
  225. // find the highest confidence
  226. auto pos = m_templateList.begin();
  227. CCrySingleDocTemplate::Confidence bestMatch = CCrySingleDocTemplate::noAttempt;
  228. CCrySingleDocTemplate* pBestTemplate = nullptr;
  229. CCryEditDoc* pOpenDocument = nullptr;
  230. if (filename[0] == '\"')
  231. {
  232. ++filename;
  233. }
  234. QString szPath = QString::fromUtf8(filename);
  235. if (szPath.endsWith('"'))
  236. {
  237. szPath.remove(szPath.length() - 1, 1);
  238. }
  239. while (pos != m_templateList.end())
  240. {
  241. auto pTemplate = *(pos++);
  242. CCrySingleDocTemplate::Confidence match;
  243. assert(pOpenDocument == nullptr);
  244. match = pTemplate->MatchDocType(szPath.toUtf8().data(), pOpenDocument);
  245. if (match > bestMatch)
  246. {
  247. bestMatch = match;
  248. pBestTemplate = pTemplate;
  249. }
  250. if (match == CCrySingleDocTemplate::yesAlreadyOpen)
  251. {
  252. break; // stop here
  253. }
  254. }
  255. if (!reopenIfSame && pOpenDocument != nullptr)
  256. {
  257. return pOpenDocument;
  258. }
  259. if (pBestTemplate == nullptr)
  260. {
  261. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to open document."));
  262. return nullptr;
  263. }
  264. return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), addToMostRecentFileList, false);
  265. }
  266. //////////////////////////////////////////////////////////////////////////////
  267. // CCryEditApp
  268. #undef ON_COMMAND
  269. #define ON_COMMAND(id, method) \
  270. MainWindow::instance()->GetActionManager()->RegisterActionHandler(id, this, &CCryEditApp::method);
  271. #undef ON_COMMAND_RANGE
  272. #define ON_COMMAND_RANGE(idStart, idEnd, method) \
  273. for (int i = idStart; i <= idEnd; ++i) \
  274. ON_COMMAND(i, method);
  275. AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once);
  276. CCryEditApp* CCryEditApp::s_currentInstance = nullptr;
  277. /////////////////////////////////////////////////////////////////////////////
  278. // CCryEditApp construction
  279. CCryEditApp::CCryEditApp()
  280. {
  281. s_currentInstance = this;
  282. m_sPreviewFile[0] = 0;
  283. AzFramework::AssetSystemInfoBus::Handler::BusConnect();
  284. AzFramework::AssetSystemStatusBus::Handler::BusConnect();
  285. m_disableIdleProcessingCounter = 0;
  286. EditorIdleProcessingBus::Handler::BusConnect();
  287. }
  288. //////////////////////////////////////////////////////////////////////////
  289. CCryEditApp::~CCryEditApp()
  290. {
  291. EditorIdleProcessingBus::Handler::BusDisconnect();
  292. AzFramework::AssetSystemStatusBus::Handler::BusDisconnect();
  293. AzFramework::AssetSystemInfoBus::Handler::BusDisconnect();
  294. s_currentInstance = nullptr;
  295. }
  296. CCryEditApp* CCryEditApp::instance()
  297. {
  298. return s_currentInstance;
  299. }
  300. class CEditCommandLineInfo
  301. {
  302. public:
  303. bool m_bTest = false;
  304. bool m_bAutoLoadLevel = false;
  305. bool m_bExport = false;
  306. bool m_bExportTexture = false;
  307. bool m_bConsoleMode = false;
  308. bool m_bNullRenderer = false;
  309. bool m_bDeveloperMode = false;
  310. bool m_bRunPythonScript = false;
  311. bool m_bRunPythonTestScript = false;
  312. bool m_bShowVersionInfo = false;
  313. QString m_exportFile;
  314. QString m_strFileName;
  315. QString m_appRoot;
  316. QString m_logFile;
  317. QString m_pythonArgs;
  318. QString m_pythonTestCase;
  319. QString m_execFile;
  320. QString m_execLineCmd;
  321. bool m_bSkipWelcomeScreenDialog = false;
  322. bool m_bAutotestMode = false;
  323. struct CommandLineStringOption
  324. {
  325. QString name;
  326. QString description;
  327. QString valueName;
  328. };
  329. CEditCommandLineInfo()
  330. {
  331. bool dummy;
  332. QCommandLineParser parser;
  333. parser.addHelpOption();
  334. parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
  335. parser.setApplicationDescription(QObject::tr("O3DE Editor"));
  336. // nsDocumentRevisionDebugMode is an argument that the macOS system passed into an App bundle that is being debugged.
  337. // Need to include it here so that Qt argument parser does not error out.
  338. bool nsDocumentRevisionsDebugMode = false;
  339. const std::vector<std::pair<QString, bool&> > options = {
  340. { "export", m_bExport },
  341. { "exportTexture", m_bExportTexture },
  342. { "test", m_bTest },
  343. { "auto_level_load", m_bAutoLoadLevel },
  344. { "BatchMode", m_bConsoleMode },
  345. { "NullRenderer", m_bNullRenderer },
  346. { "devmode", m_bDeveloperMode },
  347. { "runpython", m_bRunPythonScript },
  348. { "runpythontest", m_bRunPythonTestScript },
  349. { "version", m_bShowVersionInfo },
  350. { "NSDocumentRevisionsDebugMode", nsDocumentRevisionsDebugMode},
  351. { "skipWelcomeScreenDialog", m_bSkipWelcomeScreenDialog},
  352. { "autotest_mode", m_bAutotestMode},
  353. { "regdumpall", dummy },
  354. { "attach-debugger", dummy }, // Attaches a debugger for the current application
  355. { "wait-for-debugger", dummy }, // Waits until a debugger is attached to the current application
  356. };
  357. QString dummyString;
  358. const std::vector<std::pair<CommandLineStringOption, QString&> > stringOptions = {
  359. {{"logfile", "File name of the log file to write out to.", "logfile"}, m_logFile},
  360. {{"runpythonargs", "Command-line argument string to pass to the python script if --runpython or --runpythontest was used.", "runpythonargs"}, m_pythonArgs},
  361. {{"pythontestcase", "Test case name of python test script if --runpythontest was used.", "pythontestcase"}, m_pythonTestCase},
  362. {{"exec", "cfg file to run on startup, used for systems like automation", "exec"}, m_execFile},
  363. {{"rhi", "Command-line argument to force which rhi to use", "rhi"}, dummyString },
  364. {{"rhi-device-validation", "Command-line argument to configure rhi validation", "rhi-device-validation"}, dummyString },
  365. {{"exec_line", "command to run on startup, used for systems like automation", "exec_line"}, m_execLineCmd},
  366. {{"regset", "Command-line argument to override settings registry values", "regset"}, dummyString},
  367. {{"regremove", "Deletes a value within the global settings registry at the JSON pointer path @key", "regremove"}, dummyString},
  368. {{"regdump", "Sets a value within the global settings registry at the JSON pointer path @key with value of @value", "regdump"}, dummyString},
  369. {{"project-path", "Supplies the path to the project that the Editor should use", "project-path"}, dummyString},
  370. {{"engine-path", "Supplies the path to the engine", "engine-path"}, dummyString},
  371. {{"project-cache-path", "Path to the project cache", "project-cache-path"}, dummyString},
  372. {{"project-user-path", "Path to the project user path", "project-user-path"}, dummyString},
  373. {{"project-log-path", "Path to the project log path", "project-log-path"}, dummyString}
  374. // add dummy entries here to prevent QCommandLineParser error-ing out on cmd line args that will be parsed later
  375. };
  376. parser.addPositionalArgument("file", QCoreApplication::translate("main", "file to open"));
  377. for (const auto& option : options)
  378. {
  379. parser.addOption(QCommandLineOption(option.first));
  380. }
  381. for (const auto& option : stringOptions)
  382. {
  383. parser.addOption(QCommandLineOption(option.first.name, option.first.description, option.first.valueName));
  384. }
  385. QStringList args = qApp->arguments();
  386. #ifdef Q_OS_WIN32
  387. for (QString& arg : args)
  388. {
  389. if (!arg.isEmpty() && arg[0] == '/')
  390. {
  391. arg[0] = '-'; // QCommandLineParser only supports - and -- prefixes
  392. }
  393. }
  394. #endif
  395. if (!parser.parse(args))
  396. {
  397. AZ_TracePrintf("QT CommandLine Parser", "QT command line parsing warned with message %s."
  398. " Has the QCommandLineParser had these options added to it", parser.errorText().toUtf8().constData());
  399. }
  400. // Get boolean options
  401. const int numOptions = static_cast<int>(options.size());
  402. for (int i = 0; i < numOptions; ++i)
  403. {
  404. options[i].second = parser.isSet(options[i].first);
  405. }
  406. // Get string options
  407. for (auto& option : stringOptions)
  408. {
  409. option.second = parser.value(option.first.valueName);
  410. }
  411. m_bExport = m_bExport || m_bExportTexture;
  412. const QStringList positionalArgs = parser.positionalArguments();
  413. if (!positionalArgs.isEmpty())
  414. {
  415. m_strFileName = positionalArgs.first();
  416. if (positionalArgs.first().at(0) != '[')
  417. {
  418. m_exportFile = positionalArgs.first();
  419. }
  420. }
  421. }
  422. };
  423. struct SharedData
  424. {
  425. bool raise = false;
  426. char text[_MAX_PATH];
  427. };
  428. /////////////////////////////////////////////////////////////////////////////
  429. // CTheApp::FirstInstance
  430. // FirstInstance checks for an existing instance of the application.
  431. // If one is found, it is activated.
  432. //
  433. // This function uses a technique similar to that described in KB
  434. // article Q141752 to locate the previous instance of the application. .
  435. bool CCryEditApp::FirstInstance(bool bForceNewInstance)
  436. {
  437. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  438. sem.acquire();
  439. {
  440. FixDanglingSharedMemory(O3DEEditorClassName);
  441. }
  442. sem.release();
  443. m_mutexApplication = new QSharedMemory(O3DEEditorClassName);
  444. if (!m_mutexApplication->create(sizeof(SharedData)) && !bForceNewInstance)
  445. {
  446. m_mutexApplication->attach();
  447. // another instance is already running - activate it
  448. sem.acquire();
  449. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  450. data->raise = true;
  451. if (m_bPreviewMode)
  452. {
  453. // IF in preview mode send this window copy data message to load new preview file.
  454. azstrcpy(data->text, MAX_PATH, m_sPreviewFile);
  455. }
  456. return false;
  457. }
  458. else
  459. {
  460. m_mutexApplication->attach();
  461. // this is the first instance
  462. sem.acquire();
  463. ::memset(m_mutexApplication->data(), 0, m_mutexApplication->size());
  464. sem.release();
  465. QTimer* t = new QTimer(this);
  466. connect(t, &QTimer::timeout, this, [this]() {
  467. QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1);
  468. sem.acquire();
  469. SharedData* data = reinterpret_cast<SharedData*>(m_mutexApplication->data());
  470. QString preview = QString::fromLatin1(data->text);
  471. if (data->raise)
  472. {
  473. QWidget* w = MainWindow::instance();
  474. w->setWindowState((w->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
  475. w->raise();
  476. w->activateWindow();
  477. data->raise = false;
  478. }
  479. if (!preview.isEmpty())
  480. {
  481. // Load this file
  482. LoadFile(preview);
  483. data->text[0] = 0;
  484. }
  485. sem.release();
  486. });
  487. t->start(1000);
  488. return true;
  489. }
  490. return true;
  491. }
  492. //////////////////////////////////////////////////////////////////////////
  493. void CCryEditApp::OnFileSave()
  494. {
  495. if (m_savingLevel)
  496. {
  497. return;
  498. }
  499. const QScopedValueRollback<bool> rollback(m_savingLevel, true);
  500. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  501. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  502. prefabIntegrationInterface->SaveCurrentPrefab();
  503. // when attempting to save, update the last known location using the active camera transform
  504. AzToolsFramework::StoreViewBookmarkLastKnownLocationFromActiveCamera();
  505. }
  506. //////////////////////////////////////////////////////////////////////////
  507. void CCryEditApp::OnUpdateDocumentReady(QAction* action)
  508. {
  509. action->setEnabled(GetIEditor()
  510. && GetIEditor()->GetDocument()
  511. && GetIEditor()->GetDocument()->IsDocumentReady()
  512. && !m_bIsExportingLegacyData
  513. && !m_creatingNewLevel
  514. && !m_openingLevel
  515. && !m_savingLevel);
  516. }
  517. //////////////////////////////////////////////////////////////////////////
  518. void CCryEditApp::OnUpdateFileOpen(QAction* action)
  519. {
  520. action->setEnabled(!m_bIsExportingLegacyData && !m_creatingNewLevel && !m_openingLevel && !m_savingLevel);
  521. }
  522. bool CCryEditApp::ShowEnableDisableGemDialog(const QString& title, const QString& message)
  523. {
  524. const QString informativeMessage = QObject::tr("Please follow the instructions <a href=\"https://www.o3de.org/docs/user-guide/project-config/add-remove-gems/\">here</a>, after which the Editor will be re-launched automatically.");
  525. QMessageBox box(AzToolsFramework::GetActiveWindow());
  526. box.addButton(QObject::tr("Continue"), QMessageBox::AcceptRole);
  527. box.addButton(QObject::tr("Back"), QMessageBox::RejectRole);
  528. box.setWindowTitle(title);
  529. box.setText(message);
  530. box.setInformativeText(informativeMessage);
  531. box.setWindowFlags(box.windowFlags() & ~Qt::WindowContextHelpButtonHint);
  532. if (box.exec() == QMessageBox::AcceptRole)
  533. {
  534. // Called from a modal dialog with the main window as its parent. Best not to close the main window while the dialog is still active.
  535. QTimer::singleShot(0, MainWindow::instance(), &MainWindow::close);
  536. return true;
  537. }
  538. return false;
  539. }
  540. QString CCryEditApp::ShowWelcomeDialog()
  541. {
  542. WelcomeScreenDialog wsDlg(MainWindow::instance());
  543. wsDlg.SetRecentFileList(GetRecentFileList());
  544. wsDlg.exec();
  545. QString levelName = wsDlg.GetLevelPath();
  546. return levelName;
  547. }
  548. //////////////////////////////////////////////////////////////////////////
  549. // Needed to work with custom memory manager.
  550. //////////////////////////////////////////////////////////////////////////
  551. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool bMakeVisible /*= true*/)
  552. {
  553. return OpenDocumentFile(lpszPathName, true, bMakeVisible);
  554. }
  555. CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(const char* lpszPathName, bool addToMostRecentFileList, [[maybe_unused]] bool bMakeVisible)
  556. {
  557. CCryEditDoc* pCurDoc = GetIEditor()->GetDocument();
  558. if (pCurDoc)
  559. {
  560. if (!pCurDoc->SaveModified())
  561. {
  562. return nullptr;
  563. }
  564. }
  565. if (!pCurDoc)
  566. {
  567. pCurDoc = qobject_cast<CCryEditDoc*>(m_documentClass->newInstance());
  568. if (pCurDoc == nullptr)
  569. return nullptr;
  570. pCurDoc->setParent(this);
  571. }
  572. pCurDoc->SetModifiedFlag(false);
  573. if (lpszPathName == nullptr)
  574. {
  575. pCurDoc->SetTitle(tr("Untitled"));
  576. pCurDoc->OnNewDocument();
  577. }
  578. else
  579. {
  580. pCurDoc->OnOpenDocument(lpszPathName);
  581. pCurDoc->SetPathName(lpszPathName);
  582. if (addToMostRecentFileList)
  583. {
  584. CCryEditApp::instance()->AddToRecentFileList(lpszPathName);
  585. }
  586. }
  587. return pCurDoc;
  588. }
  589. CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(const char* lpszPathName, CCryEditDoc*& rpDocMatch)
  590. {
  591. assert(lpszPathName != nullptr);
  592. rpDocMatch = nullptr;
  593. // go through all documents
  594. CCryEditDoc* pDoc = GetIEditor()->GetDocument();
  595. if (pDoc)
  596. {
  597. QString prevPathName = pDoc->GetLevelPathName();
  598. // all we need to know here is whether it is the same file as before.
  599. if (!prevPathName.isEmpty())
  600. {
  601. // QFileInfo is guaranteed to return true iff the two paths refer to the same path.
  602. if (QFileInfo(prevPathName) == QFileInfo(QString::fromUtf8(lpszPathName)))
  603. {
  604. // already open
  605. rpDocMatch = pDoc;
  606. return yesAlreadyOpen;
  607. }
  608. }
  609. }
  610. // see if it matches our default suffix
  611. const QString strFilterExt = EditorUtils::LevelFile::GetDefaultFileExtension();
  612. const QString strOldFilterExt = EditorUtils::LevelFile::GetOldCryFileExtension();
  613. // see if extension matches
  614. assert(strFilterExt[0] == '.');
  615. QString strDot = "." + Path::GetExt(lpszPathName);
  616. if (!strDot.isEmpty())
  617. {
  618. if(strDot == strFilterExt || strDot == strOldFilterExt)
  619. {
  620. return yesAttemptNative; // extension matches, looks like ours
  621. }
  622. }
  623. // otherwise we will guess it may work
  624. return yesAttemptForeign;
  625. }
  626. /////////////////////////////////////////////////////////////////////////////
  627. namespace
  628. {
  629. AZStd::mutex g_splashScreenStateLock;
  630. enum ESplashScreenState
  631. {
  632. eSplashScreenState_Init, eSplashScreenState_Started, eSplashScreenState_Destroy
  633. };
  634. ESplashScreenState g_splashScreenState = eSplashScreenState_Init;
  635. IInitializeUIInfo* g_pInitializeUIInfo = nullptr;
  636. QWidget* g_splashScreen = nullptr;
  637. }
  638. QString FormatVersion([[maybe_unused]] const SFileVersion& v)
  639. {
  640. if (QObject::tr("%1").arg(O3DE_BUILD_VERSION) == "0")
  641. {
  642. return QObject::tr("Development Build");
  643. }
  644. return QObject::tr("Version %1").arg(O3DE_BUILD_VERSION);
  645. }
  646. QString FormatRichTextCopyrightNotice()
  647. {
  648. // copyright symbol is HTML Entity = &#xA9;
  649. QString copyrightHtmlSymbol = "&#xA9;";
  650. QString copyrightString = QObject::tr("Copyright %1 Contributors to the Open 3D Engine Project");
  651. return copyrightString.arg(copyrightHtmlSymbol);
  652. }
  653. void CCryEditApp::AssetSystemWaiting()
  654. {
  655. QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
  656. }
  657. /////////////////////////////////////////////////////////////////////////////
  658. void CCryEditApp::ShowSplashScreen(CCryEditApp* app)
  659. {
  660. g_splashScreenStateLock.lock();
  661. CStartupLogoDialog* splashScreen = new CStartupLogoDialog(CStartupLogoDialog::Loading, FormatVersion(app->m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  662. g_pInitializeUIInfo = splashScreen;
  663. g_splashScreen = splashScreen;
  664. g_splashScreenState = eSplashScreenState_Started;
  665. g_splashScreenStateLock.unlock();
  666. splashScreen->show();
  667. QObject::connect(splashScreen, &QObject::destroyed, splashScreen, [=]
  668. {
  669. AZStd::scoped_lock lock(g_splashScreenStateLock);
  670. g_pInitializeUIInfo = nullptr;
  671. g_splashScreen = nullptr;
  672. });
  673. }
  674. /////////////////////////////////////////////////////////////////////////////
  675. void CCryEditApp::CreateSplashScreen()
  676. {
  677. if (!m_bConsoleMode && !IsInAutotestMode())
  678. {
  679. // Create startup output splash
  680. ShowSplashScreen(this);
  681. GetIEditor()->Notify(eNotify_OnSplashScreenCreated);
  682. }
  683. else
  684. {
  685. // Create console
  686. m_pConsoleDialog = new CConsoleDialog();
  687. m_pConsoleDialog->show();
  688. g_pInitializeUIInfo = m_pConsoleDialog;
  689. }
  690. }
  691. /////////////////////////////////////////////////////////////////////////////
  692. void CCryEditApp::CloseSplashScreen()
  693. {
  694. if (CStartupLogoDialog::instance())
  695. {
  696. delete CStartupLogoDialog::instance();
  697. g_splashScreenStateLock.lock();
  698. g_splashScreenState = eSplashScreenState_Destroy;
  699. g_splashScreenStateLock.unlock();
  700. }
  701. GetIEditor()->Notify(eNotify_OnSplashScreenDestroyed);
  702. }
  703. /////////////////////////////////////////////////////////////////////////////
  704. void CCryEditApp::OutputStartupMessage(QString str)
  705. {
  706. g_splashScreenStateLock.lock();
  707. if (g_pInitializeUIInfo)
  708. {
  709. g_pInitializeUIInfo->SetInfoText(str.toUtf8().data());
  710. }
  711. g_splashScreenStateLock.unlock();
  712. }
  713. //////////////////////////////////////////////////////////////////////////
  714. void CCryEditApp::InitFromCommandLine(CEditCommandLineInfo& cmdInfo)
  715. {
  716. m_bConsoleMode |= cmdInfo.m_bConsoleMode;
  717. inEditorBatchMode = AZ::Environment::CreateVariable<bool>("InEditorBatchMode", m_bConsoleMode);
  718. m_bTestMode |= cmdInfo.m_bTest;
  719. m_bSkipWelcomeScreenDialog = cmdInfo.m_bSkipWelcomeScreenDialog || !cmdInfo.m_execFile.isEmpty() || !cmdInfo.m_execLineCmd.isEmpty() || cmdInfo.m_bAutotestMode;
  720. m_bExportMode = cmdInfo.m_bExport;
  721. m_bRunPythonTestScript = cmdInfo.m_bRunPythonTestScript;
  722. m_bRunPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  723. m_execFile = cmdInfo.m_execFile;
  724. m_execLineCmd = cmdInfo.m_execLineCmd;
  725. m_bAutotestMode = cmdInfo.m_bAutotestMode || cmdInfo.m_bConsoleMode;
  726. if (m_bExportMode)
  727. {
  728. m_exportFile = cmdInfo.m_exportFile;
  729. }
  730. // Do we have a passed filename ?
  731. if (!cmdInfo.m_strFileName.isEmpty())
  732. {
  733. if (!m_bRunPythonScript && IsPreviewableFileType(cmdInfo.m_strFileName.toUtf8().constData()))
  734. {
  735. m_bPreviewMode = true;
  736. azstrncpy(m_sPreviewFile, _MAX_PATH, cmdInfo.m_strFileName.toUtf8().constData(), _MAX_PATH);
  737. }
  738. }
  739. if (cmdInfo.m_bAutoLoadLevel)
  740. {
  741. m_bLevelLoadTestMode = true;
  742. gEnv->bNoAssertDialog = true;
  743. CEditorAutoLevelLoadTest::Instance();
  744. }
  745. }
  746. /////////////////////////////////////////////////////////////////////////////
  747. AZ::Outcome<void, AZStd::string> CCryEditApp::InitGameSystem(HWND hwndForInputSystem)
  748. {
  749. CGameEngine* pGameEngine = new CGameEngine;
  750. AZ::Outcome<void, AZStd::string> initOutcome = pGameEngine->Init(m_bPreviewMode, m_bTestMode, qApp->arguments().join(" ").toUtf8().data(), g_pInitializeUIInfo, hwndForInputSystem);
  751. if (!initOutcome.IsSuccess())
  752. {
  753. return initOutcome;
  754. }
  755. AZ_Assert(pGameEngine, "Game engine initialization failed, but initOutcome returned success.");
  756. m_pEditor->SetGameEngine(pGameEngine);
  757. // needs to be called after CrySystem has been loaded.
  758. gSettings.LoadDefaultGamePaths();
  759. return AZ::Success();
  760. }
  761. /////////////////////////////////////////////////////////////////////////////
  762. bool CCryEditApp::CheckIfAlreadyRunning()
  763. {
  764. bool bForceNewInstance = false;
  765. if (!m_bPreviewMode)
  766. {
  767. FixDanglingSharedMemory(O3DEApplicationName);
  768. m_mutexApplication = new QSharedMemory(O3DEApplicationName);
  769. if (!m_mutexApplication->create(16))
  770. {
  771. // Don't prompt the user in non-interactive export mode. Instead, default to allowing multiple instances to
  772. // run simultaneously, so that multiple level exports can be run in parallel on the same machine.
  773. // NOTE: If you choose to do this, be sure to export *different* levels, since nothing prevents multiple runs
  774. // from trying to write to the same level at the same time.
  775. // If we're running interactively, let's ask and make sure the user actually intended to do this.
  776. if (!m_bExportMode && QMessageBox::question(AzToolsFramework::GetActiveWindow(), QObject::tr("Too many apps"), QObject::tr("There is already an Open 3D Engine application running\nDo you want to start another one?")) != QMessageBox::Yes)
  777. {
  778. return false;
  779. }
  780. bForceNewInstance = true;
  781. }
  782. }
  783. if (!FirstInstance(bForceNewInstance))
  784. {
  785. return false;
  786. }
  787. return true;
  788. }
  789. /////////////////////////////////////////////////////////////////////////////
  790. bool CCryEditApp::InitGame()
  791. {
  792. if (!m_bPreviewMode)
  793. {
  794. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  795. Log((QString("project_path = %1").arg(!projectPath.empty() ? projectPath.c_str() : "<not set>")).toUtf8().data());
  796. ICVar* pVar = gEnv->pConsole->GetCVar("sys_localization_folder");
  797. const char* sLocalizationFolder = pVar ? pVar->GetString() : nullptr;
  798. Log((QString("sys_localization_folder = ") + (sLocalizationFolder && sLocalizationFolder[0] ? sLocalizationFolder : "<not set>")).toUtf8().data());
  799. OutputStartupMessage("Starting Game...");
  800. if (!GetIEditor()->GetGameEngine()->InitGame(nullptr))
  801. {
  802. return false;
  803. }
  804. }
  805. //////////////////////////////////////////////////////////////////////////
  806. // Apply settings post engine initialization.
  807. GetIEditor()->GetDisplaySettings()->PostInitApply();
  808. gSettings.PostInitApply();
  809. return true;
  810. }
  811. /////////////////////////////////////////////////////////////////////////////
  812. void CCryEditApp::InitPlugins()
  813. {
  814. OutputStartupMessage("Loading Plugins...");
  815. // Load the plugins
  816. {
  817. GetIEditor()->LoadPlugins();
  818. #if defined(AZ_PLATFORM_WINDOWS)
  819. C3DConnexionDriver* p3DConnexionDriver = new C3DConnexionDriver;
  820. GetIEditor()->GetPluginManager()->RegisterPlugin(0, p3DConnexionDriver);
  821. #endif
  822. }
  823. }
  824. ////////////////////////////////////////////////////////////////////////////
  825. // Be careful when calling this function: it should be called after
  826. // everything else has finished initializing, otherwise, certain things
  827. // aren't set up yet. If in doubt, wrap it in a QTimer::singleShot(0ms);
  828. void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo)
  829. {
  830. const char* defaultExtension = EditorUtils::LevelFile::GetDefaultFileExtension();
  831. const char* oldExtension = EditorUtils::LevelFile::GetOldCryFileExtension();
  832. if (m_bPreviewMode)
  833. {
  834. // Load geometry object.
  835. if (!cmdInfo.m_strFileName.isEmpty())
  836. {
  837. LoadFile(cmdInfo.m_strFileName);
  838. }
  839. }
  840. else if (m_bExportMode && !m_exportFile.isEmpty())
  841. {
  842. GetIEditor()->SetModifiedFlag(false);
  843. GetIEditor()->SetModifiedModule(eModifiedNothing);
  844. auto pDocument = OpenDocumentFile(m_exportFile.toUtf8().constData());
  845. if (pDocument)
  846. {
  847. GetIEditor()->SetModifiedFlag(false);
  848. GetIEditor()->SetModifiedModule(eModifiedNothing);
  849. ExportLevel(cmdInfo.m_bExport, cmdInfo.m_bExportTexture, true);
  850. // Terminate process.
  851. CLogFile::WriteLine("Editor: Terminate Process after export");
  852. }
  853. // the call to quit() must be posted to the event queue because the app is currently not yet running.
  854. // if we were to call quit() right now directly, the app would ignore it.
  855. QTimer::singleShot(0, QCoreApplication::instance(), &QCoreApplication::quit);
  856. return;
  857. }
  858. else if ((cmdInfo.m_strFileName.endsWith(defaultExtension, Qt::CaseInsensitive))
  859. || (cmdInfo.m_strFileName.endsWith(oldExtension, Qt::CaseInsensitive)))
  860. {
  861. auto pDocument = OpenDocumentFile(cmdInfo.m_strFileName.toUtf8().constData());
  862. if (pDocument)
  863. {
  864. GetIEditor()->SetModifiedFlag(false);
  865. GetIEditor()->SetModifiedModule(eModifiedNothing);
  866. }
  867. }
  868. else
  869. {
  870. //////////////////////////////////////////////////////////////////////////
  871. //It can happen that if you are switching between projects and you have auto load set that
  872. //you could inadvertently load the wrong project and not know it, you would think you are editing
  873. //one level when in fact you are editing the old one. This can happen if both projects have the same
  874. //relative path... which is often the case when branching.
  875. // Ex. D:\cryengine\dev\ gets branched to D:\cryengine\branch\dev
  876. // Now you have gamesdk in both roots and therefore GameSDK\Levels\Singleplayer\Forest in both
  877. // If you execute the branch the m_pRecentFileList will be an absolute path to the old gamesdk,
  878. // then if auto load is set simply takes the old level and loads it in the new branch...
  879. //I would question ever trying to load a level not in our gamesdk, what happens when there are things that
  880. //an not exist in the level when built in a different gamesdk.. does it erase them, most likely, then you
  881. //just screwed up the level for everyone in the other gamesdk...
  882. //So if we are auto loading a level outside our current gamesdk we should act as though the flag
  883. //was unset and pop the dialog which should be in the correct location. This is not fool proof, but at
  884. //least this its a compromise that doesn't automatically do something you probably shouldn't.
  885. bool autoloadLastLevel = gSettings.bAutoloadLastLevelAtStartup;
  886. if (autoloadLastLevel
  887. && GetRecentFileList()
  888. && GetRecentFileList()->GetSize())
  889. {
  890. QString gamePath = Path::GetEditingGameDataFolder().c_str();
  891. Path::ConvertSlashToBackSlash(gamePath);
  892. gamePath = Path::ToUnixPath(gamePath.toLower());
  893. gamePath = Path::AddSlash(gamePath);
  894. QString fullPath = GetRecentFileList()->m_arrNames[0];
  895. Path::ConvertSlashToBackSlash(fullPath);
  896. fullPath = Path::ToUnixPath(fullPath.toLower());
  897. fullPath = Path::AddSlash(fullPath);
  898. if (fullPath.indexOf(gamePath, 0) != 0)
  899. {
  900. autoloadLastLevel = false;
  901. }
  902. }
  903. //////////////////////////////////////////////////////////////////////////
  904. QString levelName;
  905. bool isLevelNameValid = false;
  906. bool doLevelNeedLoading = true;
  907. const bool runningPythonScript = cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript;
  908. AZ::EBusLogicalResult<bool, AZStd::logical_or<bool> > skipStartupUIProcess(false);
  909. AzToolsFramework::EditorEvents::Bus::BroadcastResult(
  910. skipStartupUIProcess, &AzToolsFramework::EditorEvents::Bus::Events::SkipEditorStartupUI);
  911. if (!skipStartupUIProcess.value)
  912. {
  913. do
  914. {
  915. isLevelNameValid = false;
  916. doLevelNeedLoading = true;
  917. if (gSettings.bShowDashboardAtStartup
  918. && !runningPythonScript
  919. && !m_bConsoleMode
  920. && !m_bSkipWelcomeScreenDialog
  921. && !m_bPreviewMode
  922. && !autoloadLastLevel)
  923. {
  924. levelName = ShowWelcomeDialog();
  925. }
  926. else if (autoloadLastLevel
  927. && GetRecentFileList()
  928. && GetRecentFileList()->GetSize())
  929. {
  930. levelName = GetRecentFileList()->m_arrNames[0];
  931. }
  932. if (levelName.isEmpty())
  933. {
  934. break;
  935. }
  936. if (levelName == "new")
  937. {
  938. //implies that the user has clicked the create new level option
  939. bool wasCreateLevelOperationCancelled = false;
  940. bool isNewLevelCreationSuccess = false;
  941. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  942. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  943. {
  944. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  945. if (isNewLevelCreationSuccess == true)
  946. {
  947. doLevelNeedLoading = false;
  948. isLevelNameValid = true;
  949. }
  950. }
  951. ;
  952. }
  953. else
  954. {
  955. //implies that the user wants to open an existing level
  956. doLevelNeedLoading = true;
  957. isLevelNameValid = true;
  958. }
  959. } while (!isLevelNameValid);// if we reach here and levelName is not valid ,it implies that the user has clicked cancel on the create new level dialog
  960. // load level
  961. if (doLevelNeedLoading && !levelName.isEmpty())
  962. {
  963. if (!CFileUtil::Exists(levelName, false))
  964. {
  965. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  966. return;
  967. }
  968. QString str;
  969. str = tr("Loading level %1 ...").arg(levelName);
  970. OutputStartupMessage(str);
  971. OpenDocumentFile(levelName.toUtf8().data());
  972. }
  973. }
  974. }
  975. }
  976. /////////////////////////////////////////////////////////////////////////////
  977. bool CCryEditApp::InitConsole()
  978. {
  979. // Execute command from cmdline -exec_line if applicable
  980. if (!m_execLineCmd.isEmpty())
  981. {
  982. gEnv->pConsole->ExecuteString(QString("%1").arg(m_execLineCmd).toLocal8Bit());
  983. }
  984. // Execute cfg from cmdline -exec if applicable
  985. if (!m_execFile.isEmpty())
  986. {
  987. gEnv->pConsole->ExecuteString(QString("exec %1").arg(m_execFile).toLocal8Bit());
  988. }
  989. // Execute special configs.
  990. gEnv->pConsole->ExecuteString("exec editor_autoexec.cfg");
  991. gEnv->pConsole->ExecuteString("exec editor.cfg");
  992. gEnv->pConsole->ExecuteString("exec user.cfg");
  993. GetISystem()->ExecuteCommandLine();
  994. return true;
  995. }
  996. /////////////////////////////////////////////////////////////////////////////
  997. void CCryEditApp::CompileCriticalAssets() const
  998. {
  999. // regardless of what is set in the bootstrap wait for AP to be ready
  1000. // wait a maximum of 100 milliseconds and pump the system event loop until empty
  1001. struct AssetsInQueueNotification
  1002. : public AzFramework::AssetSystemInfoBus::Handler
  1003. {
  1004. void CountOfAssetsInQueue(const int& count) override
  1005. {
  1006. CCryEditApp::OutputStartupMessage(QString("Asset Processor working... %1 jobs remaining.").arg(count));
  1007. }
  1008. };
  1009. AssetsInQueueNotification assetsInQueueNotifcation;
  1010. assetsInQueueNotifcation.BusConnect();
  1011. bool ready{};
  1012. while (!ready)
  1013. {
  1014. AzFramework::AssetSystemRequestBus::BroadcastResult(ready, &AzFramework::AssetSystemRequestBus::Events::WaitUntilAssetProcessorReady, AZStd::chrono::milliseconds(100));
  1015. if (!ready)
  1016. {
  1017. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty);
  1018. }
  1019. }
  1020. assetsInQueueNotifcation.BusDisconnect();
  1021. AZ_TracePrintf("Editor", "CriticalAssetsCompiled\n");
  1022. // Signal the "CriticalAssetsCompiled" lifecycle event
  1023. // Also reload the "assetcatalog.xml" if it exists
  1024. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1025. {
  1026. // Reload the assetcatalog.xml at this point again
  1027. // Start Monitoring Asset changes over the network and load the AssetCatalog
  1028. auto LoadCatalog = [settingsRegistry](AZ::Data::AssetCatalogRequests* assetCatalogRequests)
  1029. {
  1030. if (AZ::IO::FixedMaxPath assetCatalogPath;
  1031. settingsRegistry->Get(assetCatalogPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_CacheRootFolder))
  1032. {
  1033. assetCatalogPath /= "assetcatalog.xml";
  1034. assetCatalogRequests->LoadCatalog(assetCatalogPath.c_str());
  1035. }
  1036. };
  1037. CCryEditApp::OutputStartupMessage(QString("Loading Asset Catalog..."));
  1038. AZ::Data::AssetCatalogRequestBus::Broadcast(AZStd::move(LoadCatalog));
  1039. // Only signal the event *after* the asset catalog has been loaded.
  1040. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "CriticalAssetsCompiled", R"({})");
  1041. }
  1042. CCryEditApp::OutputStartupMessage(QString("Asset Processor is now ready."));
  1043. }
  1044. bool CCryEditApp::ConnectToAssetProcessor() const
  1045. {
  1046. bool connectedToAssetProcessor = false;
  1047. // When the AssetProcessor is already launched it should take less than a second to perform a connection
  1048. // but when the AssetProcessor needs to be launch it could take up to 15 seconds to have the AssetProcessor initialize
  1049. // and able to negotiate a connection when running a debug build
  1050. // and to negotiate a connection
  1051. // Setting the connectTimeout to 3 seconds if not set within the settings registry
  1052. AZStd::chrono::seconds connectTimeout(3);
  1053. // Initialize the launchAssetProcessorTimeout to 15 seconds by default and check the settings registry for an override
  1054. AZStd::chrono::seconds launchAssetProcessorTimeout(15);
  1055. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  1056. if (settingsRegistry)
  1057. {
  1058. AZ::s64 timeoutValue{};
  1059. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1060. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "connect_ap_timeout"))
  1061. {
  1062. connectTimeout = AZStd::chrono::seconds(timeoutValue);
  1063. }
  1064. // Reset timeout integer
  1065. timeoutValue = {};
  1066. if (AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, timeoutValue,
  1067. AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "launch_ap_timeout"))
  1068. {
  1069. launchAssetProcessorTimeout = AZStd::chrono::seconds(timeoutValue);
  1070. }
  1071. }
  1072. CCryEditApp::OutputStartupMessage(QString("Connecting to Asset Processor... "));
  1073. AzFramework::AssetSystem::ConnectionSettings connectionSettings;
  1074. AzFramework::AssetSystem::ReadConnectionSettingsFromSettingsRegistry(connectionSettings);
  1075. connectionSettings.m_launchAssetProcessorOnFailedConnection = true;
  1076. connectionSettings.m_connectionDirection = AzFramework::AssetSystem::ConnectionSettings::ConnectionDirection::ConnectToAssetProcessor;
  1077. connectionSettings.m_connectionIdentifier = AzFramework::AssetSystem::ConnectionIdentifiers::Editor;
  1078. connectionSettings.m_loggingCallback = [](AZStd::string_view logData)
  1079. {
  1080. CCryEditApp::OutputStartupMessage(QString::fromUtf8(logData.data(), aznumeric_cast<int>(logData.size())));
  1081. };
  1082. AzFramework::AssetSystemRequestBus::BroadcastResult(connectedToAssetProcessor, &AzFramework::AssetSystemRequestBus::Events::EstablishAssetProcessorConnection, connectionSettings);
  1083. if (connectedToAssetProcessor)
  1084. {
  1085. AZ_TracePrintf("Editor", "Connected to Asset Processor\n");
  1086. CCryEditApp::OutputStartupMessage(QString("Connected to Asset Processor"));
  1087. CompileCriticalAssets();
  1088. return true;
  1089. }
  1090. AZ_TracePrintf("Editor", "Failed to connect to Asset Processor\n");
  1091. CCryEditApp::OutputStartupMessage(QString("Failed to connect to Asset Processor"));
  1092. return false;
  1093. }
  1094. //! This handles the normal logging of Python output in the Editor by outputting
  1095. //! the data to both the Editor Console and the Editor.log file
  1096. struct CCryEditApp::PythonOutputHandler
  1097. : public AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  1098. {
  1099. PythonOutputHandler()
  1100. {
  1101. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect();
  1102. }
  1103. ~PythonOutputHandler() override
  1104. {
  1105. AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect();
  1106. }
  1107. int GetOrder() override
  1108. {
  1109. return 0;
  1110. }
  1111. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  1112. {
  1113. AZ_TracePrintf("python_test", "%.*s", static_cast<int>(message.size()), message.data());
  1114. }
  1115. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  1116. {
  1117. AZ_Error("python_test", false, "%.*s", static_cast<int>(message.size()), message.data());
  1118. }
  1119. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  1120. {
  1121. AZ_Error("python_test", false, "EXCEPTION: %.*s", static_cast<int>(message.size()), message.data());
  1122. }
  1123. };
  1124. //! Outputs Python test script print() to stdout
  1125. //! If an exception happens in a Python test script, the process terminates
  1126. struct PythonTestOutputHandler final
  1127. : public CCryEditApp::PythonOutputHandler
  1128. {
  1129. PythonTestOutputHandler() = default;
  1130. ~PythonTestOutputHandler() override = default;
  1131. void OnTraceMessage(AZStd::string_view message) override
  1132. {
  1133. PythonOutputHandler::OnTraceMessage(message);
  1134. printf("%.*s\n", static_cast<int>(message.size()), message.data());
  1135. }
  1136. void OnErrorMessage(AZStd::string_view message) override
  1137. {
  1138. PythonOutputHandler::OnErrorMessage(message);
  1139. printf("ERROR: %.*s\n", static_cast<int>(message.size()), message.data());
  1140. }
  1141. void OnExceptionMessage(AZStd::string_view message) override
  1142. {
  1143. PythonOutputHandler::OnExceptionMessage(message);
  1144. printf("EXCEPTION: %.*s\n", static_cast<int>(message.size()), message.data());
  1145. }
  1146. };
  1147. void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo)
  1148. {
  1149. if (cmdInfo.m_bRunPythonTestScript)
  1150. {
  1151. m_pythonOutputHandler = AZStd::make_shared<PythonTestOutputHandler>();
  1152. }
  1153. else
  1154. {
  1155. m_pythonOutputHandler = AZStd::make_shared<PythonOutputHandler>();
  1156. }
  1157. using namespace AzToolsFramework;
  1158. if (cmdInfo.m_bRunPythonScript || cmdInfo.m_bRunPythonTestScript)
  1159. {
  1160. // Separates the compound string of semicolon separated values into a vector of values
  1161. const auto extractSeparatedValues = [](const AZStd::string& compoundValues)
  1162. {
  1163. AZStd::vector<AZStd::string_view> values;
  1164. AZ::StringFunc::TokenizeVisitor(
  1165. compoundValues.c_str(),
  1166. [&values](AZStd::string_view elem)
  1167. {
  1168. values.push_back(elem);
  1169. },
  1170. ';',
  1171. false /* keepEmptyStrings */
  1172. );
  1173. return values;
  1174. };
  1175. // Reads the contents of the specified file and returns a string of said contents
  1176. const auto readFileContents = [](const AZStd::string& path) -> AZStd::string
  1177. {
  1178. const auto fileSize = AZ::IO::SystemFile::Length(path.c_str());
  1179. if (fileSize == 0)
  1180. {
  1181. return "";
  1182. }
  1183. AZStd::vector<char> buffer(fileSize + 1);
  1184. buffer[fileSize] = '\0';
  1185. if (!AZ::IO::SystemFile::Read(path.c_str(), buffer.data()))
  1186. {
  1187. return "";
  1188. }
  1189. return AZStd::string(buffer.begin(), buffer.end());
  1190. };
  1191. // We support specifying multiple files in the cmdline by separating them with ';'
  1192. // If a semicolon list of .py files is provided we look at the arg string
  1193. AZStd::string scriptFileStr;
  1194. if (cmdInfo.m_strFileName.endsWith(".py"))
  1195. {
  1196. // cmdInfo data is only available on startup, copy it
  1197. scriptFileStr = cmdInfo.m_strFileName.toUtf8().constData();
  1198. }
  1199. else if (cmdInfo.m_strFileName.endsWith(".txt"))
  1200. {
  1201. // Otherwise, we look to see if we can read the file for test modules
  1202. // The file is expected to contain a single semicolon separated string of Editor pytest modules
  1203. if (scriptFileStr = readFileContents(cmdInfo.m_strFileName.toUtf8().data()); scriptFileStr.empty())
  1204. {
  1205. AZ_Error(
  1206. "RunInitPythonScript",
  1207. false, "Failed to read the file containing a semi colon separated list of python modules");
  1208. return;
  1209. }
  1210. }
  1211. else
  1212. {
  1213. AZ_Error("RunInitPythonScript", false, "Failed to read Python files from --runpythontest arg. "
  1214. "Expects a semi colon separated list of python modules or a file containing a semi colon separated list of python modules");
  1215. return;
  1216. }
  1217. // Extract the discrete python script files
  1218. const auto fileList = extractSeparatedValues(scriptFileStr);
  1219. if (cmdInfo.m_pythonArgs.length() > 0 || cmdInfo.m_bRunPythonTestScript)
  1220. {
  1221. QByteArray pythonArgsStr = cmdInfo.m_pythonArgs.toUtf8();
  1222. AZStd::vector<AZStd::string_view> pythonArgs;
  1223. AZ::StringFunc::TokenizeVisitor(pythonArgsStr.constData(),
  1224. [&pythonArgs](AZStd::string_view elem)
  1225. {
  1226. pythonArgs.push_back(elem);
  1227. }, ' '
  1228. );
  1229. if (cmdInfo.m_bRunPythonTestScript)
  1230. {
  1231. // We support specifying multiple test case names in the cmdline by separating them
  1232. // with ';', either in a text file or as a string
  1233. AZStd::string testCaseStr;
  1234. if (cmdInfo.m_pythonTestCase.endsWith(".txt"))
  1235. {
  1236. // A path to the file containing the test case names has been provided as the argument
  1237. if (testCaseStr = readFileContents(cmdInfo.m_pythonTestCase.toUtf8().data()); testCaseStr.empty())
  1238. {
  1239. AZ_Error(
  1240. "RunInitPythonScript",
  1241. false,
  1242. "Failed to read Python files from --pythontestcase arg. "
  1243. "Expects a semi colon separated list of python test case names or a file containing a semi colon separated list of "
  1244. "python test case names");
  1245. return;
  1246. }
  1247. }
  1248. else
  1249. {
  1250. // Test case names have been passed as the argument
  1251. testCaseStr = cmdInfo.m_pythonTestCase.toUtf8().data();
  1252. }
  1253. // Extract the discrete python test case names
  1254. const auto testCaseList = extractSeparatedValues(testCaseStr);
  1255. // The number of python script files must match the number of test case names for the test case names
  1256. // to properly correlate with their invoking scripts
  1257. if (fileList.size() != testCaseList.size())
  1258. {
  1259. AZ_Error(
  1260. "RunInitPythonScript",
  1261. false,
  1262. "The number of supplied test scripts (%zu) did not match the number of supplied test case names (%zu)",
  1263. fileList.size(), testCaseList.size());
  1264. return;
  1265. }
  1266. bool success = true;
  1267. auto ExecuteByFilenamesTests = [&pythonArgs, &fileList, &testCaseList, &success](EditorPythonRunnerRequests* pythonRunnerRequests)
  1268. {
  1269. for (int i = 0; i < fileList.size(); ++i)
  1270. {
  1271. bool cur_success = pythonRunnerRequests->ExecuteByFilenameAsTest(fileList[i], testCaseList[i], pythonArgs);
  1272. success = success && cur_success;
  1273. }
  1274. };
  1275. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesTests);
  1276. if (success)
  1277. {
  1278. // Close the editor gracefully as the test has completed
  1279. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  1280. QTimer::singleShot(0, qApp, &QApplication::closeAllWindows);
  1281. }
  1282. else
  1283. {
  1284. // Close down the application with 0xF exit code indicating failure of the test
  1285. AZ::Debug::Trace::Terminate(0xF);
  1286. }
  1287. }
  1288. else
  1289. {
  1290. auto ExecuteByFilenamesWithArgs = [&pythonArgs, &fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1291. {
  1292. for (AZStd::string_view filename : fileList)
  1293. {
  1294. pythonRunnerRequests->ExecuteByFilenameWithArgs(filename, pythonArgs);
  1295. }
  1296. };
  1297. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenamesWithArgs);
  1298. }
  1299. }
  1300. else
  1301. {
  1302. auto ExecuteByFilenames = [&fileList](EditorPythonRunnerRequests* pythonRunnerRequests)
  1303. {
  1304. for (AZStd::string_view filename : fileList)
  1305. {
  1306. pythonRunnerRequests->ExecuteByFilename(filename);
  1307. }
  1308. };
  1309. EditorPythonRunnerRequestBus::Broadcast(ExecuteByFilenames);
  1310. }
  1311. }
  1312. }
  1313. /////////////////////////////////////////////////////////////////////////////
  1314. // CCryEditApp initialization
  1315. bool CCryEditApp::InitInstance()
  1316. {
  1317. QElapsedTimer startupTimer;
  1318. startupTimer.start();
  1319. m_pEditor = new CEditorImpl();
  1320. // parameters must be parsed early to capture arguments for test bootstrap
  1321. CEditCommandLineInfo cmdInfo;
  1322. InitFromCommandLine(cmdInfo);
  1323. qobject_cast<Editor::EditorQtApplication*>(qApp)->Initialize(); // Must be done after CEditorImpl() is created
  1324. m_pEditor->Initialize();
  1325. // let anything listening know that they can use the IEditor now
  1326. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyIEditorAvailable, m_pEditor);
  1327. if (cmdInfo.m_bShowVersionInfo)
  1328. {
  1329. CStartupLogoDialog startupDlg(CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1330. startupDlg.exec();
  1331. return false;
  1332. }
  1333. RegisterReflectedVarHandlers();
  1334. CreateSplashScreen();
  1335. // Register the application's document templates. Document templates
  1336. // serve as the connection between documents, frame windows and views
  1337. CCrySingleDocTemplate* pDocTemplate = CCrySingleDocTemplate::create<CCryEditDoc>();
  1338. m_pDocManager = new CCryDocManager;
  1339. ((CCryDocManager*)m_pDocManager)->SetDefaultTemplate(pDocTemplate);
  1340. auto mainWindow = new MainWindow();
  1341. #ifdef Q_OS_MACOS
  1342. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionDisabled);
  1343. #else
  1344. auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons);
  1345. #endif
  1346. mainWindowWrapper->setGuest(mainWindow);
  1347. HWND mainWindowWrapperHwnd = (HWND)mainWindowWrapper->winId();
  1348. AZ::IO::FixedMaxPath engineRootPath;
  1349. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1350. {
  1351. settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  1352. }
  1353. QDir engineRoot = QString::fromUtf8(engineRootPath.c_str(), aznumeric_cast<int>(engineRootPath.Native().size()));
  1354. AzQtComponents::StyleManager::addSearchPaths(
  1355. QStringLiteral("style"),
  1356. engineRoot.filePath(QStringLiteral("Code/Editor/Style")),
  1357. QStringLiteral(":/Assets/Editor/Style"),
  1358. engineRootPath);
  1359. AzQtComponents::StyleManager::setStyleSheet(mainWindow, QStringLiteral("style:Editor.qss"));
  1360. // Note: we should use getNativeHandle to get the HWND from the widget, but
  1361. // it returns an invalid handle unless the widget has been shown and polished and even then
  1362. // it sometimes returns an invalid handle.
  1363. // So instead, we use winId(), which does consistently work
  1364. //mainWindowWrapperHwnd = QtUtil::getNativeHandle(mainWindowWrapper);
  1365. // Connect to the AssetProcessor at this point
  1366. // It will be launched if not running
  1367. ConnectToAssetProcessor();
  1368. CCryEditApp::OutputStartupMessage(QString("Initializing Game System..."));
  1369. auto initGameSystemOutcome = InitGameSystem(mainWindowWrapperHwnd);
  1370. if (!initGameSystemOutcome.IsSuccess())
  1371. {
  1372. return false;
  1373. }
  1374. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1375. {
  1376. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacySystemInterfaceCreated", R"({})");
  1377. }
  1378. // Process some queued events come from system init
  1379. // Such as asset catalog loaded notification.
  1380. // There are some systems need to load configurations from assets for post initialization but before loading level
  1381. AZ::TickBus::ExecuteQueuedEvents();
  1382. qobject_cast<Editor::EditorQtApplication*>(qApp)->LoadSettings();
  1383. // Create Sandbox user folder if necessary
  1384. AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(Path::GetUserSandboxFolder().toUtf8().data());
  1385. if (!InitGame())
  1386. {
  1387. if (gEnv && gEnv->pLog)
  1388. {
  1389. gEnv->pLog->LogError("Game can not be initialized, InitGame() failed.");
  1390. }
  1391. if (!cmdInfo.m_bExport)
  1392. {
  1393. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Game can not be initialized, please refer to the editor log file"));
  1394. }
  1395. return false;
  1396. }
  1397. // Meant to be called before MainWindow::Initialize
  1398. InitPlugins();
  1399. CCryEditApp::OutputStartupMessage(QString("Initializing Main Window..."));
  1400. mainWindow->Initialize();
  1401. GetIEditor()->GetCommandManager()->RegisterAutoCommands();
  1402. mainWindowWrapper->enableSaveRestoreGeometry("O3DE", "O3DE", "mainWindowGeometry");
  1403. m_pDocManager->OnFileNew();
  1404. if (MainWindow::instance())
  1405. {
  1406. if (m_bConsoleMode || IsInAutotestMode())
  1407. {
  1408. AZ::Environment::FindVariable<int>("assertVerbosityLevel").Set(1);
  1409. m_pConsoleDialog->raise();
  1410. }
  1411. else
  1412. {
  1413. MainWindow::instance()->show();
  1414. MainWindow::instance()->raise();
  1415. MainWindow::instance()->update();
  1416. MainWindow::instance()->setFocus();
  1417. #if AZ_TRAIT_OS_PLATFORM_APPLE
  1418. QWindow* window = mainWindowWrapper->windowHandle();
  1419. if (window)
  1420. {
  1421. Editor::WindowObserver* observer = new Editor::WindowObserver(window, this);
  1422. connect(observer, &Editor::WindowObserver::windowIsMovingOrResizingChanged, Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::setIsMovingOrResizing);
  1423. }
  1424. #endif
  1425. }
  1426. }
  1427. if (m_bAutotestMode)
  1428. {
  1429. ICVar* const noErrorReportWindowCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_error_report_window") : nullptr;
  1430. if (noErrorReportWindowCVar)
  1431. {
  1432. noErrorReportWindowCVar->Set(true);
  1433. }
  1434. ICVar* const showErrorDialogOnLoadCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("ed_showErrorDialogOnLoad") : nullptr;
  1435. if (showErrorDialogOnLoadCVar)
  1436. {
  1437. showErrorDialogOnLoadCVar->Set(false);
  1438. }
  1439. }
  1440. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), nullptr);
  1441. m_pEditor->InitFinished();
  1442. CCryEditApp::OutputStartupMessage(QString("Activating Python..."));
  1443. // Make sure Python is started before we attempt to restore the Editor layout, since the user
  1444. // might have custom view panes in the saved layout that will need to be registered.
  1445. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  1446. if (editorPythonEventsInterface)
  1447. {
  1448. editorPythonEventsInterface->StartPython();
  1449. }
  1450. CCryEditApp::OutputStartupMessage(QString("")); // add a blank line so that python is not blamed for anything that happens here
  1451. if (!GetIEditor()->IsInConsolewMode())
  1452. {
  1453. bool restoreDefaults = !mainWindowWrapper->restoreGeometryFromSettings();
  1454. QtViewPaneManager::instance()->RestoreLayout(restoreDefaults);
  1455. }
  1456. // Trigger the Action Manager registration hooks once all systems and Gems are initialized and listening.
  1457. AzToolsFramework::ActionManagerSystemComponent::TriggerRegistrationNotifications();
  1458. CloseSplashScreen();
  1459. // DON'T CHANGE ME!
  1460. // Test scripts listen for this line, so please don't touch this without updating them.
  1461. // We consider ourselves "initialized enough" at this stage because all further initialization may be blocked by the modal welcome screen.
  1462. CLogFile::WriteLine(QString("Engine initialized, took %1s.").arg(startupTimer.elapsed() / 1000.0, 0, 'f', 2));
  1463. // Init the level after everything else is finished initializing, otherwise, certain things aren't set up yet
  1464. QTimer::singleShot(0, this, [this, cmdInfo] {
  1465. InitLevel(cmdInfo);
  1466. });
  1467. if (!m_bConsoleMode && !m_bPreviewMode)
  1468. {
  1469. GetIEditor()->UpdateViews();
  1470. if (MainWindow::instance())
  1471. {
  1472. MainWindow::instance()->setFocus();
  1473. }
  1474. }
  1475. if (!InitConsole())
  1476. {
  1477. return true;
  1478. }
  1479. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1480. {
  1481. AZ::ComponentApplicationLifecycle::SignalEvent(*settingsRegistry, "LegacyCommandLineProcessed", R"({})");
  1482. }
  1483. if (IsInRegularEditorMode())
  1484. {
  1485. int startUpMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("startup", true);
  1486. if (startUpMacroIndex >= 0)
  1487. {
  1488. CryLogAlways("Executing the startup macro");
  1489. GetIEditor()->GetToolBoxManager()->ExecuteMacro(startUpMacroIndex, true);
  1490. }
  1491. }
  1492. if (GetIEditor()->GetCommandManager()->IsRegistered("editor.open_lnm_editor"))
  1493. {
  1494. CCommand0::SUIInfo uiInfo;
  1495. [[maybe_unused]] bool ok = GetIEditor()->GetCommandManager()->GetUIInfo("editor.open_lnm_editor", uiInfo);
  1496. assert(ok);
  1497. }
  1498. RunInitPythonScript(cmdInfo);
  1499. return true;
  1500. }
  1501. //////////////////////////////////////////////////////////////////////////
  1502. void CCryEditApp::LoadFile(QString fileName)
  1503. {
  1504. if (GetIEditor()->GetViewManager()->GetViewCount() == 0)
  1505. {
  1506. return;
  1507. }
  1508. if (MainWindow::instance() || m_pConsoleDialog)
  1509. {
  1510. SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectDisplayName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName());
  1511. }
  1512. GetIEditor()->SetModifiedFlag(false);
  1513. GetIEditor()->SetModifiedModule(eModifiedNothing);
  1514. }
  1515. //////////////////////////////////////////////////////////////////////////
  1516. inline void ExtractMenuName(QString& str)
  1517. {
  1518. // eliminate &
  1519. int pos = str.indexOf('&');
  1520. if (pos >= 0)
  1521. {
  1522. str = str.left(pos) + str.right(str.length() - pos - 1);
  1523. }
  1524. // cut the string
  1525. for (int i = 0; i < str.length(); i++)
  1526. {
  1527. if (str[i] == 9)
  1528. {
  1529. str = str.left(i);
  1530. }
  1531. }
  1532. }
  1533. //////////////////////////////////////////////////////////////////////////
  1534. void CCryEditApp::EnableAccelerator([[maybe_unused]] bool bEnable)
  1535. {
  1536. /*
  1537. if (bEnable)
  1538. {
  1539. //LoadAccelTable( MAKEINTRESOURCE(IDR_MAINFRAME) );
  1540. m_AccelManager.UpdateWndTable();
  1541. CLogFile::WriteLine( "Enable Accelerators" );
  1542. }
  1543. else
  1544. {
  1545. CMainFrame *mainFrame = (CMainFrame*)m_pMainWnd;
  1546. if (mainFrame->m_hAccelTable)
  1547. DestroyAcceleratorTable( mainFrame->m_hAccelTable );
  1548. mainFrame->m_hAccelTable = nullptr;
  1549. mainFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_GAMEACCELERATOR) );
  1550. CLogFile::WriteLine( "Disable Accelerators" );
  1551. }
  1552. */
  1553. }
  1554. //////////////////////////////////////////////////////////////////////////
  1555. void CCryEditApp::SaveAutoRemind()
  1556. {
  1557. // Added a static variable here to avoid multiple messageboxes to
  1558. // remind the user of saving the file. Many message boxes would appear as this
  1559. // is triggered by a timer even which does not stop when the message box is called.
  1560. // Used a static variable instead of a member variable because this value is not
  1561. // Needed anywhere else.
  1562. static bool boIsShowingWarning(false);
  1563. // Ingore in game mode, or if no level created, or level not modified
  1564. if (GetIEditor()->IsInGameMode() || !GetIEditor()->GetGameEngine()->IsLevelLoaded() || !GetIEditor()->GetDocument()->IsModified())
  1565. {
  1566. return;
  1567. }
  1568. if (boIsShowingWarning)
  1569. {
  1570. return;
  1571. }
  1572. boIsShowingWarning = true;
  1573. if (QMessageBox::question(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Auto Reminder: You did not save level for at least %1 minute(s)\r\nDo you want to save it now?").arg(gSettings.autoRemindTime), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  1574. {
  1575. // Save now.
  1576. GetIEditor()->SaveDocument();
  1577. }
  1578. boIsShowingWarning = false;
  1579. }
  1580. //////////////////////////////////////////////////////////////////////////
  1581. void CCryEditApp::WriteConfig()
  1582. {
  1583. IEditor* pEditor = GetIEditor();
  1584. if (pEditor && pEditor->GetDisplaySettings())
  1585. {
  1586. pEditor->GetDisplaySettings()->SaveRegistry();
  1587. }
  1588. }
  1589. // App command to run the dialog
  1590. void CCryEditApp::OnAppAbout()
  1591. {
  1592. auto* dialog = new CStartupLogoDialog(
  1593. CStartupLogoDialog::About, FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice());
  1594. auto mainWindow = MainWindow::instance();
  1595. auto geometry = dialog->geometry();
  1596. geometry.moveCenter(mainWindow->mapToGlobal(mainWindow->geometry().center()));
  1597. dialog->setGeometry(geometry);
  1598. dialog->setAttribute(Qt::WA_DeleteOnClose);
  1599. dialog->show();
  1600. }
  1601. // App command to run the Welcome to Open 3D Engine dialog
  1602. void CCryEditApp::OnAppShowWelcomeScreen()
  1603. {
  1604. // This logic is a simplified version of the startup
  1605. // flow that also shows the Welcome dialog
  1606. if (m_bIsExportingLegacyData
  1607. || m_creatingNewLevel
  1608. || m_openingLevel
  1609. || m_savingLevel)
  1610. {
  1611. QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), "The Welcome screen cannot be displayed because a level load/save is in progress.");
  1612. return;
  1613. }
  1614. QString levelName;
  1615. bool showWelcomeDialog = true;
  1616. while (showWelcomeDialog)
  1617. {
  1618. // Keep showing the Welcome dialog as long as the user cancels
  1619. // a level creation/load triggered from the Welcome dialog
  1620. levelName = ShowWelcomeDialog();
  1621. if (levelName == "new")
  1622. {
  1623. // The user has clicked on the create new level option
  1624. bool wasCreateLevelOperationCancelled = false;
  1625. bool isNewLevelCreationSuccess = false;
  1626. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  1627. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  1628. {
  1629. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  1630. }
  1631. if (isNewLevelCreationSuccess)
  1632. {
  1633. showWelcomeDialog = false;
  1634. levelName.clear();
  1635. }
  1636. }
  1637. else
  1638. {
  1639. // The user has selected an existing level to open
  1640. showWelcomeDialog = false;
  1641. }
  1642. }
  1643. if (!levelName.isEmpty())
  1644. {
  1645. // load level
  1646. if (!CFileUtil::Exists(levelName, false))
  1647. {
  1648. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Missing level"), QObject::tr("Failed to auto-load last opened level. Level file does not exist:\n\n%1").arg(levelName));
  1649. }
  1650. else
  1651. {
  1652. OpenDocumentFile(levelName.toUtf8().data());
  1653. }
  1654. }
  1655. }
  1656. void CCryEditApp::OnUpdateShowWelcomeScreen(QAction* action)
  1657. {
  1658. action->setEnabled(!m_bIsExportingLegacyData
  1659. && !m_creatingNewLevel
  1660. && !m_openingLevel
  1661. && !m_savingLevel);
  1662. }
  1663. void CCryEditApp::OnDocumentationTutorials()
  1664. {
  1665. QString webLink = tr("https://o3de.org/docs/learning-guide/");
  1666. QDesktopServices::openUrl(QUrl(webLink));
  1667. }
  1668. void CCryEditApp::OnDocumentationGlossary()
  1669. {
  1670. QString webLink = tr("https://o3de.org/docs/user-guide/appendix/glossary/");
  1671. QDesktopServices::openUrl(QUrl(webLink));
  1672. }
  1673. void CCryEditApp::OnDocumentationO3DE()
  1674. {
  1675. QString webLink = tr("https://o3de.org/docs/");
  1676. QDesktopServices::openUrl(QUrl(webLink));
  1677. }
  1678. void CCryEditApp::OnDocumentationGamelift()
  1679. {
  1680. QString webLink = tr("https://docs.aws.amazon.com/gamelift/");
  1681. QDesktopServices::openUrl(QUrl(webLink));
  1682. }
  1683. void CCryEditApp::OnDocumentationReleaseNotes()
  1684. {
  1685. QString webLink = tr("https://o3de.org/docs/release-notes/");
  1686. QDesktopServices::openUrl(QUrl(webLink));
  1687. }
  1688. void CCryEditApp::OnDocumentationGameDevBlog()
  1689. {
  1690. QString webLink = tr("https://aws.amazon.com/blogs/gamedev");
  1691. QDesktopServices::openUrl(QUrl(webLink));
  1692. }
  1693. void CCryEditApp::OnDocumentationForums()
  1694. {
  1695. QString webLink = tr("https://o3de.org/community/");
  1696. QDesktopServices::openUrl(QUrl(webLink));
  1697. }
  1698. void CCryEditApp::OnDocumentationAWSSupport()
  1699. {
  1700. QString webLink = tr("https://aws.amazon.com/contact-us");
  1701. QDesktopServices::openUrl(QUrl(webLink));
  1702. }
  1703. bool CCryEditApp::FixDanglingSharedMemory(const QString& sharedMemName) const
  1704. {
  1705. QSystemSemaphore sem(sharedMemName + "_sem", 1);
  1706. sem.acquire();
  1707. {
  1708. QSharedMemory fix(sharedMemName);
  1709. if (!fix.attach())
  1710. {
  1711. if (fix.error() != QSharedMemory::NotFound)
  1712. {
  1713. sem.release();
  1714. return false;
  1715. }
  1716. }
  1717. // fix.detach() when destructed, taking out any dangling shared memory
  1718. // on unix
  1719. }
  1720. sem.release();
  1721. return true;
  1722. }
  1723. /////////////////////////////////////////////////////////////////////////////
  1724. // CCryEditApp message handlers
  1725. int CCryEditApp::ExitInstance(int exitCode)
  1726. {
  1727. if (m_pEditor)
  1728. {
  1729. m_pEditor->OnBeginShutdownSequence();
  1730. }
  1731. qobject_cast<Editor::EditorQtApplication*>(qApp)->UnloadSettings();
  1732. if (IsInRegularEditorMode())
  1733. {
  1734. if (GetIEditor())
  1735. {
  1736. int shutDownMacroIndex = GetIEditor()->GetToolBoxManager()->GetMacroIndex("shutdown", true);
  1737. if (shutDownMacroIndex >= 0)
  1738. {
  1739. CryLogAlways("Executing the shutdown macro");
  1740. GetIEditor()->GetToolBoxManager()->ExecuteMacro(shutDownMacroIndex, true);
  1741. }
  1742. }
  1743. }
  1744. if (GetIEditor())
  1745. {
  1746. //Nobody seems to know in what case that kind of exit can happen so instrumented to see if it happens at all
  1747. if (m_pEditor)
  1748. {
  1749. m_pEditor->OnEarlyExitShutdownSequence();
  1750. }
  1751. gEnv->pLog->Flush();
  1752. // note: the intention here is to quit immediately without processing anything further
  1753. // on linux and mac, _exit has that effect
  1754. // however, on windows, _exit() still invokes CRT functions, unloads, and destructors
  1755. // so on windows, we need to use TerminateProcess
  1756. #if defined(AZ_PLATFORM_WINDOWS)
  1757. TerminateProcess(GetCurrentProcess(), exitCode);
  1758. #else
  1759. _exit(exitCode);
  1760. #endif
  1761. }
  1762. SAFE_DELETE(m_pConsoleDialog);
  1763. if (GetIEditor())
  1764. {
  1765. GetIEditor()->Notify(eNotify_OnQuit);
  1766. }
  1767. // if we're aborting due to an unexpected shutdown then don't call into objects that don't exist yet.
  1768. if ((gEnv) && (gEnv->pSystem) && (gEnv->pSystem->GetILevelSystem()))
  1769. {
  1770. gEnv->pSystem->GetILevelSystem()->UnloadLevel();
  1771. }
  1772. if (GetIEditor())
  1773. {
  1774. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  1775. }
  1776. m_bExiting = true;
  1777. HEAP_CHECK
  1778. ////////////////////////////////////////////////////////////////////////
  1779. // Executed directly before termination of the editor, just write a
  1780. // quick note to the log so that we can later see that the editor
  1781. // terminated flawlessly. Also delete temporary files.
  1782. ////////////////////////////////////////////////////////////////////////
  1783. WriteConfig();
  1784. if (m_pEditor)
  1785. {
  1786. // Ensure component entities are wiped prior to unloading plugins,
  1787. // since components may be implemented in those plugins.
  1788. AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
  1789. &AzToolsFramework::EditorEntityContextRequestBus::Events::ResetEditorContext);
  1790. // vital, so that the Qt integration can unhook itself!
  1791. m_pEditor->UnloadPlugins();
  1792. m_pEditor->Uninitialize();
  1793. }
  1794. //////////////////////////////////////////////////////////////////////////
  1795. // Quick end for editor.
  1796. if (gEnv && gEnv->pSystem)
  1797. {
  1798. gEnv->pSystem->Quit();
  1799. SAFE_RELEASE(gEnv->pSystem);
  1800. }
  1801. //////////////////////////////////////////////////////////////////////////
  1802. if (m_pEditor)
  1803. {
  1804. m_pEditor->DeleteThis();
  1805. m_pEditor = nullptr;
  1806. }
  1807. // save accelerator manager configuration.
  1808. //m_AccelManager.SaveOnExit();
  1809. #ifdef WIN32
  1810. Gdiplus::GdiplusShutdown(m_gdiplusToken);
  1811. #endif
  1812. if (m_mutexApplication)
  1813. {
  1814. delete m_mutexApplication;
  1815. }
  1816. return 0;
  1817. }
  1818. bool CCryEditApp::IsWindowInForeground()
  1819. {
  1820. return Editor::EditorQtApplication::instance()->IsActive();
  1821. }
  1822. void CCryEditApp::DisableIdleProcessing()
  1823. {
  1824. m_disableIdleProcessingCounter++;
  1825. }
  1826. void CCryEditApp::EnableIdleProcessing()
  1827. {
  1828. m_disableIdleProcessingCounter--;
  1829. AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative");
  1830. }
  1831. bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount)
  1832. {
  1833. if (0 == m_disableIdleProcessingCounter)
  1834. {
  1835. return IdleProcessing(gSettings.backgroundUpdatePeriod == -1);
  1836. }
  1837. else
  1838. {
  1839. return false;
  1840. }
  1841. }
  1842. int CCryEditApp::IdleProcessing(bool bBackgroundUpdate)
  1843. {
  1844. AZ_Assert(m_disableIdleProcessingCounter == 0, "We should not be in IdleProcessing()");
  1845. //HEAP_CHECK
  1846. if (!MainWindow::instance())
  1847. {
  1848. return 0;
  1849. }
  1850. if (!GetIEditor()->GetSystem())
  1851. {
  1852. return 0;
  1853. }
  1854. // Ensure we don't get called re-entrantly
  1855. // This can occur when a nested Qt event loop fires (e.g. by way of a modal dialog calling exec)
  1856. if (m_idleProcessingRunning)
  1857. {
  1858. return 0;
  1859. }
  1860. QScopedValueRollback<bool> guard(m_idleProcessingRunning, true);
  1861. ////////////////////////////////////////////////////////////////////////
  1862. // Call the update function of the engine
  1863. ////////////////////////////////////////////////////////////////////////
  1864. if (m_bTestMode && !bBackgroundUpdate)
  1865. {
  1866. // Terminate process.
  1867. CLogFile::WriteLine("Editor: Terminate Process");
  1868. exit(0);
  1869. }
  1870. bool bIsAppWindow = IsWindowInForeground();
  1871. bool bActive = false;
  1872. int res = 0;
  1873. if (bIsAppWindow || m_bForceProcessIdle || m_bKeepEditorActive
  1874. // Automated tests must always keep the editor active, or they can get stuck
  1875. || m_bAutotestMode || m_bRunPythonTestScript)
  1876. {
  1877. res = 1;
  1878. bActive = true;
  1879. }
  1880. if (m_bForceProcessIdle && bIsAppWindow)
  1881. {
  1882. m_bForceProcessIdle = false;
  1883. }
  1884. // focus changed
  1885. if (m_bPrevActive != bActive)
  1886. {
  1887. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, bActive, 0);
  1888. #if defined(AZ_PLATFORM_WINDOWS)
  1889. // This is required for the audio system to be notified of focus changes in the editor. After discussing it
  1890. // with the macOS team, they are working on unifying the system events between the editor and standalone
  1891. // launcher so this is only needed on windows.
  1892. if (bActive)
  1893. {
  1894. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnSetFocus);
  1895. }
  1896. else
  1897. {
  1898. AzFramework::WindowsLifecycleEvents::Bus::Broadcast(&AzFramework::WindowsLifecycleEvents::Bus::Events::OnKillFocus);
  1899. }
  1900. #endif
  1901. }
  1902. m_bPrevActive = bActive;
  1903. // Tick System Events, even in the background
  1904. AZ::ComponentApplicationRequests* componentApplicationRequests = AZ::Interface<AZ::ComponentApplicationRequests>::Get();
  1905. if (componentApplicationRequests)
  1906. {
  1907. AZ::ComponentApplication* componentApplication = componentApplicationRequests->GetApplication();
  1908. if (componentApplication)
  1909. {
  1910. componentApplication->TickSystem();
  1911. }
  1912. }
  1913. // Don't tick application if we're doing idle processing during an assert.
  1914. const bool isErrorWindowVisible = (gEnv && gEnv->pSystem->IsAssertDialogVisible());
  1915. if (isErrorWindowVisible)
  1916. {
  1917. if (m_pEditor)
  1918. {
  1919. m_pEditor->Update();
  1920. }
  1921. }
  1922. else if (bActive || (bBackgroundUpdate && !bIsAppWindow))
  1923. {
  1924. // Update Game
  1925. GetIEditor()->GetGameEngine()->Update();
  1926. if (!GetIEditor()->IsInGameMode())
  1927. {
  1928. if (m_pEditor)
  1929. {
  1930. m_pEditor->Update();
  1931. }
  1932. GetIEditor()->Notify(eNotify_OnIdleUpdate);
  1933. }
  1934. }
  1935. else
  1936. {
  1937. if (GetIEditor()->GetSystem() && GetIEditor()->GetSystem()->GetILog())
  1938. {
  1939. GetIEditor()->GetSystem()->GetILog()->Update(); // print messages from other threads
  1940. }
  1941. // If we're backgrounded and not fully background updating, idle to rate limit SystemTick
  1942. static AZ::TimeMs sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1943. const int64_t maxFrameTimeMs = ed_backgroundSystemTickCap;
  1944. if (maxFrameTimeMs > 0)
  1945. {
  1946. const int64_t maxElapsedTimeMs = maxFrameTimeMs + static_cast<int64_t>(sTimeLastMs);
  1947. const int64_t realElapsedTimeMs = static_cast<int64_t>(AZ::GetRealElapsedTimeMs());
  1948. if (maxElapsedTimeMs > realElapsedTimeMs)
  1949. {
  1950. CrySleep(aznumeric_cast<unsigned int>(maxElapsedTimeMs - realElapsedTimeMs));
  1951. }
  1952. }
  1953. sTimeLastMs = AZ::GetRealElapsedTimeMs();
  1954. }
  1955. DisplayLevelLoadErrors();
  1956. if (CConsoleSCB::GetCreatedInstance())
  1957. {
  1958. CConsoleSCB::GetCreatedInstance()->FlushText();
  1959. }
  1960. return res;
  1961. }
  1962. void CCryEditApp::DisplayLevelLoadErrors()
  1963. {
  1964. CCryEditDoc* currentLevel = GetIEditor()->GetDocument();
  1965. if (currentLevel && currentLevel->IsDocumentReady() && !m_levelErrorsHaveBeenDisplayed)
  1966. {
  1967. // Generally it takes a few idle updates for meshes to load and be processed by their components. This value
  1968. // was picked based on examining when mesh components are updated and their materials are checked for
  1969. // errors (2 updates) plus one more for good luck.
  1970. const int IDLE_FRAMES_TO_WAIT = 3;
  1971. ++m_numBeforeDisplayErrorFrames;
  1972. if (m_numBeforeDisplayErrorFrames > IDLE_FRAMES_TO_WAIT)
  1973. {
  1974. GetIEditor()->CommitLevelErrorReport();
  1975. GetIEditor()->GetErrorReport()->Display();
  1976. m_numBeforeDisplayErrorFrames = 0;
  1977. m_levelErrorsHaveBeenDisplayed = true;
  1978. }
  1979. }
  1980. }
  1981. //////////////////////////////////////////////////////////////////////////
  1982. void CCryEditApp::ExportLevel(bool /* bExportToGame */, bool /* bExportTexture */, bool /* bAutoExport */)
  1983. {
  1984. AZ_Assert(false, "Prefab system doesn't require level exports.");
  1985. return;
  1986. }
  1987. //////////////////////////////////////////////////////////////////////////
  1988. void CCryEditApp::OnEditHold()
  1989. {
  1990. GetIEditor()->GetDocument()->Hold(HOLD_FETCH_FILE);
  1991. }
  1992. //////////////////////////////////////////////////////////////////////////
  1993. void CCryEditApp::OnEditFetch()
  1994. {
  1995. GetIEditor()->GetDocument()->Fetch(HOLD_FETCH_FILE);
  1996. }
  1997. //////////////////////////////////////////////////////////////////////////
  1998. bool CCryEditApp::UserExportToGame(bool /* bNoMsgBox */)
  1999. {
  2000. AZ_Assert(false, "Export Level should no longer exist.");
  2001. return false;
  2002. }
  2003. void CCryEditApp::ExportToGame(bool /* bNoMsgBox */)
  2004. {
  2005. AZ_Assert(false, "Prefab system no longer exports levels.");
  2006. return;
  2007. }
  2008. void CCryEditApp::OnFileExportToGameNoSurfaceTexture()
  2009. {
  2010. UserExportToGame(false);
  2011. }
  2012. void CCryEditApp::OnMoveObject()
  2013. {
  2014. ////////////////////////////////////////////////////////////////////////
  2015. // Move the selected object to the marker position
  2016. ////////////////////////////////////////////////////////////////////////
  2017. }
  2018. void CCryEditApp::OnRenameObj()
  2019. {
  2020. }
  2021. void CCryEditApp::OnViewSwitchToGame()
  2022. {
  2023. if (IsInPreviewMode())
  2024. {
  2025. return;
  2026. }
  2027. // If switching on game mode...
  2028. if (!GetIEditor()->IsInGameMode())
  2029. {
  2030. // If simulation mode is enabled...
  2031. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  2032. if (flags & SETTINGS_PHYSICS)
  2033. {
  2034. // Disable simulation mode
  2035. OnSwitchPhysics();
  2036. // Schedule for next frame to enable game mode
  2037. AZ::Interface<AZ::IEventScheduler>::Get()->AddCallback(
  2038. [this] { OnViewSwitchToGame(); },
  2039. AZ::Name("Enable Game Mode"), AZ::Time::ZeroTimeMs);
  2040. return;
  2041. }
  2042. }
  2043. // close all open menus
  2044. auto activePopup = qApp->activePopupWidget();
  2045. if (qobject_cast<QMenu*>(activePopup))
  2046. {
  2047. activePopup->hide();
  2048. }
  2049. // TODO: Add your command handler code here
  2050. bool inGame = !GetIEditor()->IsInGameMode();
  2051. GetIEditor()->SetInGameMode(inGame);
  2052. }
  2053. void CCryEditApp::OnViewSwitchToGameFullScreen()
  2054. {
  2055. ed_previewGameInFullscreen_once = true;
  2056. OnViewSwitchToGame();
  2057. }
  2058. //////////////////////////////////////////////////////////////////////////
  2059. void CCryEditApp::OnEditLevelData()
  2060. {
  2061. auto dir = QFileInfo(GetIEditor()->GetDocument()->GetLevelPathName()).dir();
  2062. CFileUtil::EditTextFile(dir.absoluteFilePath("leveldata.xml").toUtf8().data());
  2063. }
  2064. //////////////////////////////////////////////////////////////////////////
  2065. void CCryEditApp::OnFileEditLogFile()
  2066. {
  2067. QString file = CLogFile::GetLogFileName();
  2068. QString fullPathName = Path::GamePathToFullPath(file);
  2069. QDesktopServices::openUrl(QUrl::fromLocalFile(fullPathName));
  2070. }
  2071. //////////////////////////////////////////////////////////////////////////
  2072. void CCryEditApp::OnFileEditEditorini()
  2073. {
  2074. CFileUtil::EditTextFile(EDITOR_CFG_FILE);
  2075. }
  2076. void CCryEditApp::OnPreferences()
  2077. {
  2078. /*
  2079. //////////////////////////////////////////////////////////////////////////////
  2080. // Accels edit by CPropertyPage
  2081. CAcceleratorManager tmpAccelManager;
  2082. tmpAccelManager = m_AccelManager;
  2083. CAccelMapPage page(&tmpAccelManager);
  2084. CPropertySheet sheet;
  2085. sheet.SetTitle( _T("Preferences") );
  2086. sheet.AddPage(&page);
  2087. if (sheet.DoModal() == IDOK) {
  2088. m_AccelManager = tmpAccelManager;
  2089. m_AccelManager.UpdateWndTable();
  2090. }
  2091. */
  2092. }
  2093. void CCryEditApp::OnOpenProjectManagerSettings()
  2094. {
  2095. OpenProjectManager("UpdateProject");
  2096. }
  2097. void CCryEditApp::OnOpenProjectManagerNew()
  2098. {
  2099. OpenProjectManager("CreateProject");
  2100. }
  2101. void CCryEditApp::OnOpenProjectManager()
  2102. {
  2103. OpenProjectManager("Projects");
  2104. }
  2105. void CCryEditApp::OpenProjectManager(const AZStd::string& screen)
  2106. {
  2107. // provide the current project path for in case we want to update the project
  2108. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2109. const AZStd::vector<AZStd::string> commandLineOptions {
  2110. "--screen", screen,
  2111. "--project-path", AZStd::string::format(R"("%s")", projectPath.c_str()) };
  2112. bool launchSuccess = AzFramework::ProjectManager::LaunchProjectManager(commandLineOptions);
  2113. if (!launchSuccess)
  2114. {
  2115. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QObject::tr("Failed to launch O3DE Project Manager"), QObject::tr("Failed to find or start the O3dE Project Manager"));
  2116. }
  2117. }
  2118. //////////////////////////////////////////////////////////////////////////
  2119. void CCryEditApp::OnUndo()
  2120. {
  2121. //GetIEditor()->GetObjectManager()->UndoLastOp();
  2122. GetIEditor()->Undo();
  2123. }
  2124. //////////////////////////////////////////////////////////////////////////
  2125. void CCryEditApp::OnRedo()
  2126. {
  2127. GetIEditor()->Redo();
  2128. }
  2129. //////////////////////////////////////////////////////////////////////////
  2130. void CCryEditApp::OnUpdateRedo(QAction* action)
  2131. {
  2132. if (GetIEditor()->GetUndoManager()->IsHaveRedo())
  2133. {
  2134. action->setEnabled(true);
  2135. }
  2136. else
  2137. {
  2138. action->setEnabled(false);
  2139. }
  2140. }
  2141. //////////////////////////////////////////////////////////////////////////
  2142. void CCryEditApp::OnUpdateUndo(QAction* action)
  2143. {
  2144. if (GetIEditor()->GetUndoManager()->IsHaveUndo())
  2145. {
  2146. action->setEnabled(true);
  2147. }
  2148. else
  2149. {
  2150. action->setEnabled(false);
  2151. }
  2152. }
  2153. //////////////////////////////////////////////////////////////////////////
  2154. void CCryEditApp::OnSwitchPhysics()
  2155. {
  2156. if (GetIEditor()->GetGameEngine() && !GetIEditor()->GetGameEngine()->GetSimulationMode() && !GetIEditor()->GetGameEngine()->IsLevelLoaded())
  2157. {
  2158. // Don't allow physics to be toggled on if we haven't loaded a level yet
  2159. return;
  2160. }
  2161. QWaitCursor wait;
  2162. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_START, 0, 0);
  2163. uint32 flags = GetIEditor()->GetDisplaySettings()->GetSettings();
  2164. if (flags & SETTINGS_PHYSICS)
  2165. {
  2166. flags &= ~SETTINGS_PHYSICS;
  2167. }
  2168. else
  2169. {
  2170. flags |= SETTINGS_PHYSICS;
  2171. }
  2172. GetIEditor()->GetDisplaySettings()->SetSettings(flags);
  2173. if ((flags & SETTINGS_PHYSICS) == 0)
  2174. {
  2175. GetIEditor()->GetGameEngine()->SetSimulationMode(false);
  2176. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 0, 0);
  2177. }
  2178. else
  2179. {
  2180. GetIEditor()->GetGameEngine()->SetSimulationMode(true);
  2181. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, 1, 0);
  2182. }
  2183. GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_END, 0, 0);
  2184. }
  2185. //////////////////////////////////////////////////////////////////////////
  2186. void CCryEditApp::OnSwitchPhysicsUpdate(QAction* action)
  2187. {
  2188. Q_ASSERT(action->isCheckable());
  2189. action->setChecked(!m_bIsExportingLegacyData && GetIEditor()->GetGameEngine()->GetSimulationMode());
  2190. }
  2191. //////////////////////////////////////////////////////////////////////////
  2192. void CCryEditApp::OnSyncPlayer()
  2193. {
  2194. GetIEditor()->GetGameEngine()->SyncPlayerPosition(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2195. }
  2196. //////////////////////////////////////////////////////////////////////////
  2197. void CCryEditApp::OnSyncPlayerUpdate(QAction* action)
  2198. {
  2199. Q_ASSERT(action->isCheckable());
  2200. action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition());
  2201. }
  2202. void CCryEditApp::OnUpdateNonGameMode(QAction* action)
  2203. {
  2204. action->setEnabled(!GetIEditor()->IsInGameMode());
  2205. }
  2206. void CCryEditApp::OnUpdateNewLevel(QAction* action)
  2207. {
  2208. action->setEnabled(!m_bIsExportingLegacyData);
  2209. }
  2210. void CCryEditApp::OnUpdatePlayGame(QAction* action)
  2211. {
  2212. action->setEnabled(!m_bIsExportingLegacyData && GetIEditor()->IsLevelLoaded());
  2213. }
  2214. //////////////////////////////////////////////////////////////////////////
  2215. CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& templateName, const QString& levelName, QString& fullyQualifiedLevelName /* ={} */)
  2216. {
  2217. // If we are creating a new level and we're in simulate mode, then switch it off before we do anything else
  2218. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2219. {
  2220. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2221. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2222. OnSwitchPhysics();
  2223. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2224. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2225. if (rootSpawnableInterface)
  2226. {
  2227. rootSpawnableInterface->ProcessSpawnableQueue();
  2228. }
  2229. }
  2230. const QScopedValueRollback<bool> rollback(m_creatingNewLevel);
  2231. m_creatingNewLevel = true;
  2232. GetIEditor()->Notify(eNotify_OnBeginCreate);
  2233. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorBeginCreate);
  2234. QString currentLevel = GetIEditor()->GetLevelFolder();
  2235. if (!currentLevel.isEmpty())
  2236. {
  2237. GetIEditor()->GetSystem()->GetIPak()->ClosePacks(currentLevel.toUtf8().data());
  2238. }
  2239. QString cryFileName = levelName.mid(levelName.lastIndexOf('/') + 1, levelName.length() - levelName.lastIndexOf('/') + 1);
  2240. QString levelPath = QStringLiteral("%1/Levels/%2/").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2241. fullyQualifiedLevelName = levelPath + cryFileName + EditorUtils::LevelFile::GetDefaultFileExtension();
  2242. //_MAX_PATH includes null terminator, so we actually want to cap at _MAX_PATH-1
  2243. if (fullyQualifiedLevelName.length() >= _MAX_PATH-1)
  2244. {
  2245. GetIEditor()->Notify(eNotify_OnEndCreate);
  2246. return ECLR_MAX_PATH_EXCEEDED;
  2247. }
  2248. // Does the directory already exist ?
  2249. if (QFileInfo(levelPath).exists())
  2250. {
  2251. GetIEditor()->Notify(eNotify_OnEndCreate);
  2252. return ECLR_ALREADY_EXISTS;
  2253. }
  2254. // Create the directory
  2255. CLogFile::WriteLine("Creating level directory");
  2256. if (!CFileUtil::CreatePath(levelPath))
  2257. {
  2258. GetIEditor()->Notify(eNotify_OnEndCreate);
  2259. return ECLR_DIR_CREATION_FAILED;
  2260. }
  2261. if (GetIEditor()->GetDocument()->IsDocumentReady())
  2262. {
  2263. m_pDocManager->OnFileNew();
  2264. }
  2265. ICVar* sv_map = gEnv->pConsole->GetCVar("sv_map");
  2266. if (sv_map)
  2267. {
  2268. sv_map->Set(levelName.toUtf8().data());
  2269. }
  2270. GetIEditor()->GetDocument()->InitEmptyLevel(128, 1);
  2271. GetIEditor()->SetStatusText("Creating Level...");
  2272. // Save the document to this folder
  2273. GetIEditor()->GetDocument()->SetPathName(fullyQualifiedLevelName);
  2274. GetIEditor()->GetGameEngine()->SetLevelPath(levelPath);
  2275. auto* service = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2276. if (service)
  2277. {
  2278. const AZStd::string templateNameString(templateName.toUtf8().constData());
  2279. service->CreateNewLevelPrefab(fullyQualifiedLevelName.toUtf8().constData(), templateNameString);
  2280. }
  2281. if (GetIEditor()->GetDocument()->Save())
  2282. {
  2283. GetIEditor()->GetGameEngine()->LoadLevel(true, true);
  2284. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0);
  2285. GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0);
  2286. }
  2287. GetIEditor()->GetDocument()->CreateDefaultLevelAssets(128, 1);
  2288. GetIEditor()->GetDocument()->SetDocumentReady(true);
  2289. GetIEditor()->SetStatusText("Ready");
  2290. // At the end of the creating level process, add this level to the MRU list
  2291. CCryEditApp::instance()->AddToRecentFileList(fullyQualifiedLevelName);
  2292. GetIEditor()->Notify(eNotify_OnEndCreate);
  2293. CrySystemEventBus::Broadcast(&CrySystemEventBus::Events::OnCryEditorEndCreate);
  2294. return ECLR_OK;
  2295. }
  2296. //////////////////////////////////////////////////////////////////////////
  2297. void CCryEditApp::OnCreateLevel()
  2298. {
  2299. if (m_creatingNewLevel)
  2300. {
  2301. return;
  2302. }
  2303. bool wasCreateLevelOperationCancelled = false;
  2304. bool isNewLevelCreationSuccess = false;
  2305. // This will show the new level dialog until a valid input has been entered by the user or until the user click cancel
  2306. while (!isNewLevelCreationSuccess && !wasCreateLevelOperationCancelled)
  2307. {
  2308. wasCreateLevelOperationCancelled = false;
  2309. isNewLevelCreationSuccess = CreateLevel(wasCreateLevelOperationCancelled);
  2310. }
  2311. }
  2312. //////////////////////////////////////////////////////////////////////////
  2313. bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled)
  2314. {
  2315. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2316. if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified)
  2317. {
  2318. auto* prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get();
  2319. auto* prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  2320. AZ_Assert(prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface is not found.");
  2321. AZ_Assert(prefabIntegrationInterface != nullptr, "PrefabIntegrationInterface is not found.");
  2322. if (prefabEditorEntityOwnershipInterface == nullptr || prefabIntegrationInterface == nullptr)
  2323. {
  2324. return false;
  2325. }
  2326. AzToolsFramework::Prefab::TemplateId rootPrefabTemplateId = prefabEditorEntityOwnershipInterface->GetRootPrefabTemplateId();
  2327. int prefabSaveSelection = prefabIntegrationInterface->HandleRootPrefabClosure(rootPrefabTemplateId);
  2328. // In order to get the accept and reject codes of QDialog and QDialogButtonBox aligned, we do (1-prefabSaveSelection) here.
  2329. // For example, QDialog::Rejected(0) is emitted when dialog is closed. But the int value corresponds to
  2330. // QDialogButtonBox::AcceptRole(0).
  2331. switch (1 - prefabSaveSelection)
  2332. {
  2333. case QDialogButtonBox::AcceptRole:
  2334. bIsDocModified = false;
  2335. break;
  2336. case QDialogButtonBox::RejectRole:
  2337. wasCreateLevelOperationCancelled = true;
  2338. return false;
  2339. case QDialogButtonBox::InvalidRole:
  2340. // Set Modified flag to false to prevent show Save unchanged dialog again
  2341. GetIEditor()->GetDocument()->SetModifiedFlag(false);
  2342. break;
  2343. }
  2344. }
  2345. const char* temporaryLevelName = GetIEditor()->GetDocument()->GetTemporaryLevelName();
  2346. CNewLevelDialog dlg;
  2347. dlg.m_level = "";
  2348. if (dlg.exec() != QDialog::Accepted)
  2349. {
  2350. wasCreateLevelOperationCancelled = true;
  2351. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2352. return false;
  2353. }
  2354. if (!GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2355. {
  2356. return false;
  2357. }
  2358. QString levelNameWithPath = dlg.GetLevel();
  2359. QString levelName = levelNameWithPath.mid(levelNameWithPath.lastIndexOf('/') + 1);
  2360. if (levelName == temporaryLevelName && GetIEditor()->GetLevelName() != temporaryLevelName)
  2361. {
  2362. GetIEditor()->GetDocument()->DeleteTemporaryLevel();
  2363. }
  2364. if (levelName.length() == 0 || !AZ::StringFunc::Path::IsValid(levelName.toUtf8().data()))
  2365. {
  2366. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level name is invalid, please choose another name."));
  2367. return false;
  2368. }
  2369. //Verify that we are not using the temporary level name
  2370. if (QString::compare(levelName, temporaryLevelName) == 0)
  2371. {
  2372. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Please enter a level name that is different from the temporary name."));
  2373. return false;
  2374. }
  2375. // We're about to start creating a level, so start recording errors to display at the end.
  2376. GetIEditor()->StartLevelErrorReportRecording();
  2377. QString fullyQualifiedLevelName;
  2378. ECreateLevelResult result = CreateLevel(dlg.GetTemplateName(), levelNameWithPath, fullyQualifiedLevelName);
  2379. if (result == ECLR_ALREADY_EXISTS)
  2380. {
  2381. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Level with this name already exists, please choose another name."));
  2382. return false;
  2383. }
  2384. else if (result == ECLR_DIR_CREATION_FAILED)
  2385. {
  2386. QString szLevelRoot = QStringLiteral("%1\\Levels\\%2").arg(Path::GetEditingGameDataFolder().c_str(), levelName);
  2387. QByteArray windowsErrorMessage(ERROR_LEN, 0);
  2388. QByteArray cwd(ERROR_LEN, 0);
  2389. DWORD dw = GetLastError();
  2390. #ifdef WIN32
  2391. wchar_t windowsErrorMessageW[ERROR_LEN];
  2392. windowsErrorMessageW[0] = L'\0';
  2393. FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2394. nullptr,
  2395. dw,
  2396. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2397. windowsErrorMessageW,
  2398. ERROR_LEN, nullptr);
  2399. _getcwd(cwd.data(), cwd.length());
  2400. AZStd::to_string(windowsErrorMessage.data(), ERROR_LEN, windowsErrorMessageW);
  2401. #else
  2402. windowsErrorMessage = strerror(dw);
  2403. cwd = QDir::currentPath().toUtf8();
  2404. #endif
  2405. QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to create level directory: %1\n Error: %2\nCurrent Path: %3").arg(szLevelRoot, windowsErrorMessage, cwd));
  2406. return false;
  2407. }
  2408. else if (result == ECLR_MAX_PATH_EXCEEDED)
  2409. {
  2410. QFileInfo info(fullyQualifiedLevelName);
  2411. const AZStd::string rawProjectDirectory = Path::GetEditingGameDataFolder();
  2412. const QString projectDirectory = QDir::toNativeSeparators(QString::fromUtf8(rawProjectDirectory.data(), static_cast<int>(rawProjectDirectory.size())));
  2413. const QString elidedLevelName = QStringLiteral("%1...%2").arg(levelName.left(10)).arg(levelName.right(10));
  2414. const QString elidedLevelFileName = QStringLiteral("%1...%2").arg(info.fileName().left(10)).arg(info.fileName().right(10));
  2415. const QString message = QObject::tr(
  2416. "The fully-qualified path for the new level exceeds the maximum supported path length of %1 characters (it's %2 characters long). Please choose a smaller name.\n\n"
  2417. "The fully-qualified path is made up of the project folder (\"%3\", %4 characters), the \"Levels\" sub-folder, a folder named for the level (\"%5\", %6 characters) and the level file (\"%7\", %8 characters), plus necessary separators.\n\n"
  2418. "Please also note that on most platforms, individual components of the path (folder/file names can't exceed approximately 255 characters)\n\n"
  2419. "Click \"Copy to Clipboard\" to copy the fully-qualified name and close this message.")
  2420. .arg(_MAX_PATH - 1).arg(fullyQualifiedLevelName.size())
  2421. .arg(projectDirectory).arg(projectDirectory.size())
  2422. .arg(elidedLevelName).arg(levelName.size())
  2423. .arg(elidedLevelFileName).arg(info.fileName().size());
  2424. QMessageBox messageBox(QMessageBox::Critical, QString(), message, QMessageBox::Ok, AzToolsFramework::GetActiveWindow());
  2425. QPushButton* copyButton = messageBox.addButton(QObject::tr("Copy to Clipboard"), QMessageBox::ActionRole);
  2426. QObject::connect(copyButton, &QPushButton::pressed, this, [fullyQualifiedLevelName]() { QGuiApplication::clipboard()->setText(fullyQualifiedLevelName); });
  2427. messageBox.exec();
  2428. return false;
  2429. }
  2430. // force the level being rendered at least once
  2431. m_bForceProcessIdle = true;
  2432. m_levelErrorsHaveBeenDisplayed = false;
  2433. return true;
  2434. }
  2435. //////////////////////////////////////////////////////////////////////////
  2436. void CCryEditApp::OnOpenLevel()
  2437. {
  2438. CLevelFileDialog levelFileDialog(true);
  2439. levelFileDialog.show();
  2440. levelFileDialog.adjustSize();
  2441. if (levelFileDialog.exec() == QDialog::Accepted)
  2442. {
  2443. OpenDocumentFile(levelFileDialog.GetFileName().toUtf8().data(), true, COpenSameLevelOptions::ReopenLevelIfSame);
  2444. }
  2445. }
  2446. //////////////////////////////////////////////////////////////////////////
  2447. CCryEditDoc* CCryEditApp::OpenDocumentFile(const char* filename, bool addToMostRecentFileList, COpenSameLevelOptions openSameLevelOptions)
  2448. {
  2449. if (m_openingLevel)
  2450. {
  2451. return GetIEditor()->GetDocument();
  2452. }
  2453. // If we are loading and we're in simulate mode, then switch it off before we do anything else
  2454. if (GetIEditor()->GetGameEngine() && GetIEditor()->GetGameEngine()->GetSimulationMode())
  2455. {
  2456. // Preserve the modified flag, we don't want this switch of physics to change that flag
  2457. bool bIsDocModified = GetIEditor()->GetDocument()->IsModified();
  2458. OnSwitchPhysics();
  2459. GetIEditor()->GetDocument()->SetModifiedFlag(bIsDocModified);
  2460. auto* rootSpawnableInterface = AzFramework::RootSpawnableInterface::Get();
  2461. if (rootSpawnableInterface)
  2462. {
  2463. rootSpawnableInterface->ProcessSpawnableQueue();
  2464. }
  2465. }
  2466. // We're about to start loading a level, so start recording errors to display at the end.
  2467. GetIEditor()->StartLevelErrorReportRecording();
  2468. const QScopedValueRollback<bool> rollback(m_openingLevel, true);
  2469. MainWindow::instance()->menuBar()->setEnabled(false);
  2470. CCryEditDoc* doc = nullptr;
  2471. bool bVisible = false;
  2472. bool bTriggerConsole = false;
  2473. doc = GetIEditor()->GetDocument();
  2474. bVisible = GetIEditor()->ShowConsole(true);
  2475. bTriggerConsole = true;
  2476. if (GetIEditor()->GetLevelIndependentFileMan()->PromptChangedFiles())
  2477. {
  2478. SandboxEditor::StartupTraceHandler openDocTraceHandler;
  2479. openDocTraceHandler.StartCollection();
  2480. if (m_bAutotestMode)
  2481. {
  2482. openDocTraceHandler.SetShowWindow(false);
  2483. }
  2484. // in this case, we set addToMostRecentFileList to always be true because adding files to the MRU list
  2485. // automatically culls duplicate and normalizes paths anyway
  2486. m_pDocManager->OpenDocumentFile(filename, addToMostRecentFileList, openSameLevelOptions);
  2487. if (openDocTraceHandler.HasAnyErrors())
  2488. {
  2489. doc->SetHasErrors();
  2490. }
  2491. }
  2492. if (bTriggerConsole)
  2493. {
  2494. GetIEditor()->ShowConsole(bVisible);
  2495. }
  2496. MainWindow::instance()->menuBar()->setEnabled(true);
  2497. m_levelErrorsHaveBeenDisplayed = false;
  2498. return doc; // the API wants a CDocument* to be returned. It seems not to be used, though, in our current state.
  2499. }
  2500. //////////////////////////////////////////////////////////////////////////
  2501. void CCryEditApp::OnResourcesReduceworkingset()
  2502. {
  2503. #ifdef WIN32 // no such thing on macOS
  2504. SetProcessWorkingSetSize(GetCurrentProcess(), std::numeric_limits<SIZE_T>::max(), std::numeric_limits<SIZE_T>::max());
  2505. #endif
  2506. }
  2507. void CCryEditApp::OnUpdateWireframe(QAction* action)
  2508. {
  2509. Q_ASSERT(action->isCheckable());
  2510. int nWireframe(R_SOLID_MODE);
  2511. ICVar* r_wireframe(gEnv->pConsole->GetCVar("r_wireframe"));
  2512. if (r_wireframe)
  2513. {
  2514. nWireframe = r_wireframe->GetIVal();
  2515. }
  2516. action->setChecked(nWireframe == R_WIREFRAME_MODE);
  2517. }
  2518. //////////////////////////////////////////////////////////////////////////
  2519. void CCryEditApp::OnViewConfigureLayout()
  2520. {
  2521. if (GetIEditor()->IsInGameMode())
  2522. {
  2523. // you may not change your viewports while game mode is running.
  2524. CryLog("You may not change viewport configuration while in game mode.");
  2525. return;
  2526. }
  2527. CLayoutWnd* layout = GetIEditor()->GetViewManager()->GetLayout();
  2528. if (layout)
  2529. {
  2530. CLayoutConfigDialog dlg;
  2531. dlg.SetLayout(layout->GetLayout());
  2532. if (dlg.exec() == QDialog::Accepted)
  2533. {
  2534. // Will kill this Pane. so must be last line in this function.
  2535. layout->CreateLayout(dlg.GetLayout());
  2536. }
  2537. }
  2538. }
  2539. //////////////////////////////////////////////////////////////////////////
  2540. void CCryEditApp::OnToolsLogMemoryUsage()
  2541. {
  2542. gEnv->pConsole->ExecuteString("SaveLevelStats");
  2543. }
  2544. //////////////////////////////////////////////////////////////////////////
  2545. void CCryEditApp::OnCustomizeKeyboard()
  2546. {
  2547. MainWindow::instance()->OnCustomizeToolbar();
  2548. }
  2549. //////////////////////////////////////////////////////////////////////////
  2550. void CCryEditApp::OnToolsScriptHelp()
  2551. {
  2552. AzToolsFramework::CScriptHelpDialog::GetInstance()->show();
  2553. }
  2554. //////////////////////////////////////////////////////////////////////////
  2555. void CCryEditApp::OnViewCycle2dviewport()
  2556. {
  2557. GetIEditor()->GetViewManager()->Cycle2DViewport();
  2558. }
  2559. //////////////////////////////////////////////////////////////////////////
  2560. void CCryEditApp::OnDisplayGotoPosition()
  2561. {
  2562. GotoPositionDialog dialog;
  2563. dialog.exec();
  2564. }
  2565. //////////////////////////////////////////////////////////////////////////
  2566. void CCryEditApp::OnFileSavelevelresources()
  2567. {
  2568. CGameResourcesExporter saver;
  2569. saver.GatherAllLoadedResources();
  2570. saver.ChooseDirectoryAndSave();
  2571. }
  2572. //////////////////////////////////////////////////////////////////////////
  2573. void CCryEditApp::OnClearRegistryData()
  2574. {
  2575. if (QMessageBox::warning(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Clear all sandbox registry data ?"),
  2576. QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
  2577. {
  2578. QSettings settings;
  2579. settings.clear();
  2580. }
  2581. }
  2582. //////////////////////////////////////////////////////////////////////////
  2583. void CCryEditApp::OnToolsPreferences()
  2584. {
  2585. EditorPreferencesDialog dlg(MainWindow::instance());
  2586. dlg.exec();
  2587. }
  2588. //////////////////////////////////////////////////////////////////////////
  2589. void CCryEditApp::OnSwitchToDefaultCamera()
  2590. {
  2591. }
  2592. //////////////////////////////////////////////////////////////////////////
  2593. void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action)
  2594. {
  2595. Q_ASSERT(action->isCheckable());
  2596. {
  2597. action->setEnabled(false);
  2598. }
  2599. }
  2600. //////////////////////////////////////////////////////////////////////////
  2601. void CCryEditApp::OnSwitchToSequenceCamera()
  2602. {
  2603. }
  2604. //////////////////////////////////////////////////////////////////////////
  2605. void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action)
  2606. {
  2607. Q_ASSERT(action->isCheckable());
  2608. {
  2609. action->setEnabled(false);
  2610. }
  2611. }
  2612. //////////////////////////////////////////////////////////////////////////
  2613. void CCryEditApp::OnSwitchToSelectedcamera()
  2614. {
  2615. }
  2616. //////////////////////////////////////////////////////////////////////////
  2617. void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action)
  2618. {
  2619. Q_ASSERT(action->isCheckable());
  2620. {
  2621. action->setEnabled(false);
  2622. }
  2623. }
  2624. //////////////////////////////////////////////////////////////////////////
  2625. void CCryEditApp::OnSwitchcameraNext()
  2626. {
  2627. }
  2628. //////////////////////////////////////////////////////////////////////////
  2629. void CCryEditApp::OnOpenAssetBrowserView()
  2630. {
  2631. QtViewPaneManager::instance()->OpenPane(LyViewPane::AssetBrowser);
  2632. }
  2633. //////////////////////////////////////////////////////////////////////////
  2634. void CCryEditApp::OnOpenTrackView()
  2635. {
  2636. QtViewPaneManager::instance()->OpenPane(LyViewPane::TrackView);
  2637. }
  2638. //////////////////////////////////////////////////////////////////////////
  2639. void CCryEditApp::OnOpenAudioControlsEditor()
  2640. {
  2641. QtViewPaneManager::instance()->OpenPane(LyViewPane::AudioControlsEditor);
  2642. }
  2643. //////////////////////////////////////////////////////////////////////////
  2644. void CCryEditApp::OnOpenUICanvasEditor()
  2645. {
  2646. QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor);
  2647. }
  2648. //////////////////////////////////////////////////////////////////////////
  2649. RecentFileList* CCryEditApp::GetRecentFileList()
  2650. {
  2651. static RecentFileList list;
  2652. return &list;
  2653. };
  2654. //////////////////////////////////////////////////////////////////////////
  2655. void CCryEditApp::AddToRecentFileList(const QString& lpszPathName)
  2656. {
  2657. // In later MFC implementations (WINVER >= 0x0601) files must exist before they can be added to the recent files list.
  2658. // Here we override the new CWinApp::AddToRecentFileList code with the old implementation to remove this requirement.
  2659. if (IsInAutotestMode())
  2660. {
  2661. // Never add to the recent file list when in auto test mode
  2662. // This would cause issues for devs running tests locally impacting their normal workflows/setups
  2663. return;
  2664. }
  2665. if (GetRecentFileList())
  2666. {
  2667. GetRecentFileList()->Add(lpszPathName);
  2668. }
  2669. // write the list immediately so it will be remembered even after a crash
  2670. if (GetRecentFileList())
  2671. {
  2672. GetRecentFileList()->WriteList();
  2673. }
  2674. else
  2675. {
  2676. CLogFile::WriteLine("ERROR: Recent File List is NULL!");
  2677. }
  2678. }
  2679. //////////////////////////////////////////////////////////////////////////
  2680. bool CCryEditApp::IsInRegularEditorMode()
  2681. {
  2682. return !IsInTestMode() && !IsInPreviewMode()
  2683. && !IsInExportMode() && !IsInConsoleMode() && !IsInLevelLoadTestMode();
  2684. }
  2685. void CCryEditApp::SetEditorWindowTitle(QString sTitleStr, QString sPreTitleStr, QString sPostTitleStr)
  2686. {
  2687. if (MainWindow::instance() || m_pConsoleDialog)
  2688. {
  2689. if (sTitleStr.isEmpty())
  2690. {
  2691. sTitleStr = QObject::tr("O3DE Editor [%1]").arg(FormatVersion(m_pEditor->GetFileVersion()));
  2692. }
  2693. if (!sPreTitleStr.isEmpty())
  2694. {
  2695. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPreTitleStr));
  2696. }
  2697. if (!sPostTitleStr.isEmpty())
  2698. {
  2699. sTitleStr.insert(sTitleStr.length(), QStringLiteral(" - %1").arg(sPostTitleStr));
  2700. }
  2701. MainWindow::instance()->setWindowTitle(sTitleStr);
  2702. if (m_pConsoleDialog)
  2703. {
  2704. m_pConsoleDialog->setWindowTitle(sTitleStr);
  2705. }
  2706. }
  2707. }
  2708. bool CCryEditApp::Command_ExportToEngine()
  2709. {
  2710. return CCryEditApp::instance()->UserExportToGame(true);
  2711. }
  2712. CMainFrame * CCryEditApp::GetMainFrame() const
  2713. {
  2714. return MainWindow::instance()->GetOldMainFrame();
  2715. }
  2716. void CCryEditApp::OpenExternalLuaDebugger(AZStd::string_view luaDebuggerUri, AZStd::string_view projectPath, AZStd::string_view enginePath, const char* files)
  2717. {
  2718. // Put together the whole Url Query String:
  2719. QUrlQuery query;
  2720. query.addQueryItem("projectPath", QString::fromUtf8(projectPath.data(), aznumeric_cast<int>(projectPath.size())));
  2721. if (!enginePath.empty())
  2722. {
  2723. query.addQueryItem("enginePath", QString::fromUtf8(enginePath.data(), aznumeric_cast<int>(enginePath.size())));
  2724. }
  2725. auto ParseFilesList = [&](AZStd::string_view filePath)
  2726. {
  2727. bool fullPathFound = false;
  2728. auto GetFullSourcePath = [&]
  2729. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2730. {
  2731. AZ::IO::Path assetFullPath;
  2732. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2733. {
  2734. fullPathFound = true;
  2735. query.addQueryItem("files[]", QString::fromUtf8(assetFullPath.c_str()));
  2736. }
  2737. };
  2738. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2739. // If the full source path could be found through the Asset System, then
  2740. // attempt to resolve the path using the FileIO instance
  2741. if (!fullPathFound)
  2742. {
  2743. AZ::IO::FixedMaxPath resolvedFilePath;
  2744. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2745. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2746. && fileIo->Exists(resolvedFilePath.c_str()))
  2747. {
  2748. query.addQueryItem("files[]", QString::fromUtf8(resolvedFilePath.c_str()));
  2749. }
  2750. }
  2751. };
  2752. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2753. QUrl luaDebuggerUrl(QString::fromUtf8(luaDebuggerUri.data(), aznumeric_cast<int>(luaDebuggerUri.size())));
  2754. luaDebuggerUrl.setQuery(query);
  2755. AZ_VerifyError("CCryEditApp", Platform::OpenUri(luaDebuggerUrl),
  2756. "Failed to start external lua debugger with URI: %s", luaDebuggerUrl.toString().toUtf8().constData());
  2757. }
  2758. void CCryEditApp::OpenLUAEditor(const char* files)
  2759. {
  2760. AZ::IO::FixedMaxPathString enginePath = AZ::Utils::GetEnginePath();
  2761. AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath();
  2762. auto registry = AZ::SettingsRegistry::Get();
  2763. if (registry)
  2764. {
  2765. AZStd::string luaDebuggerUri;
  2766. if (registry->Get(luaDebuggerUri, LuaDebuggerUriRegistryKey))
  2767. {
  2768. OpenExternalLuaDebugger(luaDebuggerUri, projectPath, enginePath, files);
  2769. return;
  2770. }
  2771. }
  2772. AZStd::string filename = "LuaIDE";
  2773. AZ::IO::FixedMaxPath executablePath = AZ::Utils::GetExecutableDirectory();
  2774. executablePath /= filename + AZ_TRAIT_OS_EXECUTABLE_EXTENSION;
  2775. if (!AZ::IO::SystemFile::Exists(executablePath.c_str()))
  2776. {
  2777. AZ_Error("LuaIDE", false, "%s not found", executablePath.c_str());
  2778. return;
  2779. }
  2780. AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo;
  2781. AZStd::vector<AZStd::string> launchCmd = { executablePath.String() };
  2782. launchCmd.emplace_back("--engine-path");
  2783. launchCmd.emplace_back(AZStd::string_view{ enginePath });
  2784. launchCmd.emplace_back("--project-path");
  2785. launchCmd.emplace_back(AZStd::string_view{ projectPath });
  2786. launchCmd.emplace_back("--launch");
  2787. launchCmd.emplace_back("lua");
  2788. auto ParseFilesList = [&launchCmd](AZStd::string_view filePath)
  2789. {
  2790. bool fullPathFound = false;
  2791. auto GetFullSourcePath = [&launchCmd, &filePath, &fullPathFound]
  2792. (AzToolsFramework::AssetSystem::AssetSystemRequest* assetSystemRequests)
  2793. {
  2794. AZ::IO::Path assetFullPath;
  2795. if(assetSystemRequests->GetFullSourcePathFromRelativeProductPath(filePath, assetFullPath.Native()))
  2796. {
  2797. fullPathFound = true;
  2798. launchCmd.emplace_back("--files");
  2799. launchCmd.emplace_back(AZStd::move(assetFullPath.Native()));
  2800. }
  2801. };
  2802. AzToolsFramework::AssetSystemRequestBus::Broadcast(AZStd::move(GetFullSourcePath));
  2803. // If the full source path could be found through the Asset System, then
  2804. // attempt to resolve the path using the FileIO instance
  2805. if (!fullPathFound)
  2806. {
  2807. AZ::IO::FixedMaxPath resolvedFilePath;
  2808. if (auto fileIo = AZ::IO::FileIOBase::GetInstance();
  2809. fileIo != nullptr && fileIo->ResolvePath(resolvedFilePath, filePath)
  2810. && fileIo->Exists(resolvedFilePath.c_str()))
  2811. {
  2812. launchCmd.emplace_back("--files");
  2813. launchCmd.emplace_back(resolvedFilePath.String());
  2814. }
  2815. }
  2816. };
  2817. AZ::StringFunc::TokenizeVisitor(files, ParseFilesList, "|");
  2818. processLaunchInfo.m_commandlineParameters = AZStd::move(launchCmd);
  2819. AZ_VerifyError("LuaIDE", AzFramework::ProcessLauncher::LaunchUnwatchedProcess(processLaunchInfo),
  2820. "Lua IDE has failed to launch at path %s", executablePath.c_str());
  2821. }
  2822. void CCryEditApp::PrintAlways(const AZStd::string& output)
  2823. {
  2824. m_stdoutRedirection.WriteBypassingRedirect(output.c_str(), static_cast<unsigned int>(output.size()));
  2825. }
  2826. QString CCryEditApp::GetRootEnginePath() const
  2827. {
  2828. return m_rootEnginePath;
  2829. }
  2830. void CCryEditApp::RedirectStdoutToNull()
  2831. {
  2832. m_stdoutRedirection.RedirectTo(AZ::IO::SystemFile::GetNullFilename());
  2833. }
  2834. void CCryEditApp::OnError(AzFramework::AssetSystem::AssetSystemErrors error)
  2835. {
  2836. AZStd::string errorMessage = "";
  2837. switch (error)
  2838. {
  2839. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_LAUNCH_ASSETPROCESSOR:
  2840. errorMessage = AZStd::string::format("Failed to start the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in.\r\n");
  2841. break;
  2842. case AzFramework::AssetSystem::ASSETSYSTEM_FAILED_TO_CONNECT_TO_ASSETPROCESSOR:
  2843. errorMessage = AZStd::string::format("Failed to connect to the Asset Processor.\r\nPlease make sure that AssetProcessor is available in the same folder the Editor is in and another copy is not already running somewhere else.\r\n");
  2844. break;
  2845. }
  2846. QMessageBox::critical(nullptr,"Error",errorMessage.c_str());
  2847. }
  2848. void CCryEditApp::OnOpenProceduralMaterialEditor()
  2849. {
  2850. QtViewPaneManager::instance()->OpenPane(LyViewPane::SubstanceEditor);
  2851. }
  2852. namespace Editor
  2853. {
  2854. //! This function returns the build system target name
  2855. AZStd::string_view GetBuildTargetName()
  2856. {
  2857. #if !defined (LY_CMAKE_TARGET)
  2858. #error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target"
  2859. #endif
  2860. return AZStd::string_view{ LY_CMAKE_TARGET };
  2861. }
  2862. }
  2863. #if defined(AZ_PLATFORM_WINDOWS)
  2864. //Due to some laptops not autoswitching to the discrete gpu correctly we are adding these
  2865. //dllspecs as defined in the amd and nvidia white papers to 'force on' the use of the
  2866. //discrete chips. This will be overriden by users setting application profiles
  2867. //and may not work on older drivers or bios. In theory this should be enough to always force on
  2868. //the discrete chips.
  2869. //http://developer.download.nvidia.com/devzone/devcenter/gamegraphics/files/OptimusRenderingPolicies.pdf
  2870. //https://community.amd.com/thread/169965
  2871. // It is unclear if this is also needed for linux or osx at this time(22/02/2017)
  2872. extern "C"
  2873. {
  2874. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  2875. __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
  2876. }
  2877. #endif
  2878. #ifdef Q_OS_WIN
  2879. #pragma comment(lib, "Shell32.lib")
  2880. #endif
  2881. extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[])
  2882. {
  2883. // Debugging utilities
  2884. for (int i = 1; i < argc; ++i)
  2885. {
  2886. if (azstricmp(argv[i], "--attach-debugger") == 0)
  2887. {
  2888. AZ::Debug::Trace::AttachDebugger();
  2889. }
  2890. else if (azstricmp(argv[i], "--wait-for-debugger") == 0)
  2891. {
  2892. AZ::Debug::Trace::WaitForDebugger();
  2893. }
  2894. }
  2895. // ensure the EditorEventsBus context gets created inside EditorLib
  2896. [[maybe_unused]] const auto& editorEventsContext = AzToolsFramework::EditorEvents::Bus::GetOrCreateContext();
  2897. // connect relevant buses to global settings
  2898. gSettings.Connect();
  2899. auto theApp = AZStd::make_unique<CCryEditApp>();
  2900. // Must be set before QApplication is initialized, so that we support HighDpi monitors, like the Retina displays
  2901. // on Windows 10
  2902. QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  2903. QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
  2904. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  2905. // QtOpenGL attributes and surface format setup.
  2906. QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
  2907. QSurfaceFormat format = QSurfaceFormat::defaultFormat();
  2908. format.setDepthBufferSize(24);
  2909. format.setStencilBufferSize(8);
  2910. format.setVersion(2, 1);
  2911. format.setProfile(QSurfaceFormat::CoreProfile);
  2912. format.setSamples(8);
  2913. format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
  2914. format.setRenderableType(QSurfaceFormat::OpenGL);
  2915. format.setSwapInterval(0);
  2916. #ifdef AZ_DEBUG_BUILD
  2917. format.setOption(QSurfaceFormat::DebugContext);
  2918. #endif
  2919. QSurfaceFormat::setDefaultFormat(format);
  2920. Editor::EditorQtApplication::InstallQtLogHandler();
  2921. AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware);
  2922. Editor::EditorQtApplication* app = Editor::EditorQtApplication::newInstance(argc, argv);
  2923. QStringList qArgs = app->arguments();
  2924. const bool is_automated_test = AZStd::any_of(qArgs.begin(), qArgs.end(),
  2925. [](const QString& elem)
  2926. {
  2927. return elem.endsWith("autotest_mode") || elem.endsWith("runpythontest");
  2928. }
  2929. );
  2930. if (is_automated_test)
  2931. {
  2932. // Nullroute all stdout to null for automated tests, this way we make sure
  2933. // that the test result output is not polluted with unrelated output data.
  2934. theApp->RedirectStdoutToNull();
  2935. }
  2936. // Hook the trace bus to catch errors, boot the AZ app after the QApplication is up
  2937. int ret = 0;
  2938. // open a scope to contain the AZToolsApp instance;
  2939. {
  2940. EditorInternal::EditorToolsApplication AZToolsApp(&argc, &argv);
  2941. {
  2942. CEditCommandLineInfo cmdInfo;
  2943. if (!cmdInfo.m_bAutotestMode && !cmdInfo.m_bConsoleMode && !cmdInfo.m_bExport && !cmdInfo.m_bExportTexture &&
  2944. !cmdInfo.m_bNullRenderer && !cmdInfo.m_bTest)
  2945. {
  2946. if (auto nativeUI = AZ::Interface<AZ::NativeUI::NativeUIRequests>::Get(); nativeUI != nullptr)
  2947. {
  2948. nativeUI->SetMode(AZ::NativeUI::Mode::ENABLED);
  2949. }
  2950. }
  2951. }
  2952. // The settings registry has been created by the AZ::ComponentApplication constructor at this point
  2953. AZ::SettingsRegistryInterface& registry = *AZ::SettingsRegistry::Get();
  2954. AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization(
  2955. registry, Editor::GetBuildTargetName());
  2956. AZ::Interface<AZ::IConsole>::Get()->PerformCommand("sv_isDedicated false");
  2957. if (!AZToolsApp.Start())
  2958. {
  2959. return -1;
  2960. }
  2961. AzToolsFramework::EditorEvents::Bus::Broadcast(&AzToolsFramework::EditorEvents::NotifyQtApplicationAvailable, app);
  2962. int exitCode = 0;
  2963. bool didCryEditStart = CCryEditApp::instance()->InitInstance();
  2964. AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close."
  2965. "\nThis could be because of incorrectly configured components, or missing required gems."
  2966. "\nSee other errors for more details.");
  2967. AzToolsFramework::EditorEventsBus::Broadcast(&AzToolsFramework::EditorEvents::NotifyEditorInitialized);
  2968. if (didCryEditStart)
  2969. {
  2970. app->EnableOnIdle();
  2971. ret = app->exec();
  2972. }
  2973. else
  2974. {
  2975. exitCode = 1;
  2976. }
  2977. CCryEditApp::instance()->ExitInstance(exitCode);
  2978. }
  2979. delete app;
  2980. gSettings.Disconnect();
  2981. return ret;
  2982. }
  2983. AZ_DECLARE_MODULE_INITIALIZATION
  2984. #include <moc_CryEdit.cpp>