ScriptCanvasFileHandling.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 <AzCore/Component/ComponentApplicationBus.h>
  9. #include <AzCore/IO/FileIO.h>
  10. #include <AzCore/IO/GenericStreams.h>
  11. #include <AzCore/Serialization/Json/JsonSerialization.h>
  12. #include <AzCore/Serialization/Json/JsonSerializationResult.h>
  13. #include <AzCore/Serialization/Json/JsonUtils.h>
  14. #include <AzCore/Serialization/SerializeContext.h>
  15. #include <AzCore/Serialization/Utils.h>
  16. #include <AzCore/Utils/Utils.h>
  17. #include <AzCore/std/string/string_view.h>
  18. #include <AzFramework/StringFunc/StringFunc.h>
  19. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  20. #include <ScriptCanvas/Asset/SubgraphInterfaceAsset.h>
  21. #include <ScriptCanvas/Bus/EditorScriptCanvasBus.h>
  22. #include <ScriptCanvas/Bus/ScriptCanvasBus.h>
  23. #include <ScriptCanvas/Components/EditorGraph.h>
  24. #include <ScriptCanvas/Components/EditorUtils.h>
  25. #include <ScriptCanvas/Core/GraphSerialization.h>
  26. #include <ScriptCanvas/Core/SerializationListener.h>
  27. #include <ScriptCanvas/Libraries/Math/MathNodeUtilities.h>
  28. #include <ScriptCanvas/Assets/ScriptCanvasFileHandling.h>
  29. namespace ScriptCanvasFileHandlingCpp
  30. {
  31. class SourceTreeLoader
  32. {
  33. public:
  34. AZ_CLASS_ALLOCATOR(SourceTreeLoader, AZ::SystemAllocator);
  35. ScriptCanvas::SourceHandle m_source;
  36. AZStd::vector<SourceTreeLoader> m_dependencies;
  37. void AssignParents(SourceTreeLoader& parent)
  38. {
  39. m_parent = &parent;
  40. for (auto& dep : m_dependencies)
  41. {
  42. dep.AssignParents(*this);
  43. }
  44. }
  45. ScriptCanvas::SourceTree ConvertToSourceTree() const
  46. {
  47. ScriptCanvas::SourceTree sourceTree;
  48. sourceTree.m_source = m_source;
  49. for (auto& dep : m_dependencies)
  50. {
  51. sourceTree.m_dependencies.push_back(dep.ConvertToSourceTree());
  52. }
  53. return sourceTree;
  54. }
  55. AZStd::optional<SourceTreeLoader> FindDependency(ScriptCanvas::SourceHandle dependency)
  56. {
  57. if (m_source.AnyEquals(dependency) && m_source.Get())
  58. {
  59. return *this;
  60. }
  61. for (auto& dep : m_dependencies)
  62. {
  63. if (auto depOptional = dep.FindDependency(dependency))
  64. {
  65. return *depOptional;
  66. }
  67. }
  68. return AZStd::nullopt;
  69. }
  70. bool IsLoading(ScriptCanvas::SourceHandle dependency, AZStd::string& path)
  71. {
  72. path += m_source.RelativePath().c_str();
  73. if (m_source.AnyEquals(dependency))
  74. {
  75. return true;
  76. }
  77. else if (m_parent)
  78. {
  79. path += " =>\n";
  80. return m_parent->IsLoading(dependency, path);
  81. }
  82. else
  83. {
  84. return false;
  85. }
  86. }
  87. SourceTreeLoader* ModRoot()
  88. {
  89. if (!m_parent)
  90. {
  91. return this;
  92. }
  93. return m_parent->ModRoot();
  94. }
  95. private:
  96. SourceTreeLoader* m_parent = nullptr;
  97. };
  98. AZ::Outcome<void, AZStd::string> LoadEditorAssetTree(
  99. SourceTreeLoader& result, ScriptCanvas::MakeInternalGraphEntitiesUnique makeUniqueEntities)
  100. {
  101. using namespace ScriptCanvas;
  102. if (!ScriptCanvasEditor::CompleteDescriptionInPlace(result.m_source))
  103. {
  104. return AZ::Failure(AZStd::string::format("LoadEditorAssetTree failed to describe graph from %s", result.m_source.ToString().c_str()));
  105. }
  106. if (!result.m_source.Get())
  107. {
  108. const auto loadResult = LoadFromFile(result.m_source.AbsolutePath().Native(), makeUniqueEntities);
  109. if (!loadResult)
  110. {
  111. return AZ::Failure
  112. ( AZStd::string::format("LoadEditorAssetTree failed to load graph from %s: %s"
  113. , result.m_source.ToString().c_str()
  114. , loadResult.ToString().c_str()));
  115. }
  116. auto absolutePath = result.m_source.AbsolutePath();
  117. result.m_source = SourceHandle::FromRelativePath(loadResult.m_handle.Data(), result.m_source.Id(), result.m_source.RelativePath().c_str());
  118. result.m_source = SourceHandle::MarkAbsolutePath(result.m_source, absolutePath);
  119. }
  120. const auto subgraphInterfaceAssetTypeID = azrtti_typeid<AZ::Data::Asset<ScriptCanvas::SubgraphInterfaceAsset>>();
  121. AZStd::vector<SourceTreeLoader> possibleDependencies;
  122. auto onBeginElement = [&subgraphInterfaceAssetTypeID, &possibleDependencies]
  123. ( void* instance
  124. , const AZ::SerializeContext::ClassData* classData
  125. , const AZ::SerializeContext::ClassElement* classElement) -> bool
  126. {
  127. if (classElement)
  128. {
  129. // if we are a pointer, then we may be pointing to a derived type.
  130. if (classElement->m_flags & AZ::SerializeContext::ClassElement::FLG_POINTER)
  131. {
  132. // if ptr is a pointer-to-pointer, cast its value to a void* (or const void*) and dereference to get to the actual object pointer.
  133. instance = *static_cast<void**>(instance);
  134. }
  135. }
  136. const auto azTypeId = classData->m_azRtti->GetTypeId();
  137. if (azTypeId == subgraphInterfaceAssetTypeID)
  138. {
  139. auto id = reinterpret_cast<AZ::Data::Asset<ScriptCanvas::SubgraphInterfaceAsset>*>(instance)->GetId();
  140. SourceTreeLoader dependencyLoader;
  141. dependencyLoader.m_source = ScriptCanvas::SourceHandle(nullptr, id.m_guid);
  142. possibleDependencies.push_back(dependencyLoader);
  143. }
  144. return true;
  145. };
  146. AZ::SerializeContext* serializeContext = nullptr;
  147. AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext);
  148. AZ_Assert(serializeContext, "LoadEditorAssetTree() ailed to retrieve serialize context!");
  149. const ScriptCanvasEditor::EditorGraph* graph = result.m_source.Get();
  150. serializeContext->EnumerateObject(graph, onBeginElement, nullptr, AZ::SerializeContext::ENUM_ACCESS_FOR_READ);
  151. for (auto& possibleDependency : possibleDependencies)
  152. {
  153. // do not count locally defined functions as dependencies
  154. if (!result.m_source.AnyEquals(possibleDependency.m_source))
  155. {
  156. // now that circular dependencies can be guarded against, load each dependency from disk only once
  157. {
  158. SourceTreeLoader dependencyLoader;
  159. dependencyLoader.m_source = possibleDependency.m_source;
  160. result.m_dependencies.push_back(dependencyLoader);
  161. result.m_dependencies.back().AssignParents(result);
  162. }
  163. SourceTreeLoader& dependentAsset = result.m_dependencies.back();
  164. AZStd::string path;
  165. if (result.IsLoading(dependentAsset.m_source, path))
  166. { // check for circular dependencies...
  167. return AZ::Failure(AZStd::string::format("LoadEditorAsset tree failed to load. Circular dependency detected: %s", path.c_str()));
  168. }
  169. else if (auto sourceTreeOptional = result.ModRoot()->FindDependency(dependentAsset.m_source))
  170. { // check at the level root if the dependency is loaded already...
  171. dependentAsset.m_source = sourceTreeOptional->m_source;
  172. }
  173. else
  174. { // ...and if not, load and add the value to the in process-loads at this step...
  175. const auto loadDependentOutcome = ScriptCanvasFileHandlingCpp::LoadEditorAssetTree(dependentAsset, makeUniqueEntities);
  176. if (!loadDependentOutcome.IsSuccess())
  177. {
  178. return AZ::Failure(AZStd::string::format("LoadEditorAssetTree failed to load graph from %s: %s"
  179. , dependentAsset.m_source.ToString().c_str(), loadDependentOutcome.GetError().c_str()));
  180. }
  181. }
  182. }
  183. }
  184. return AZ::Success();
  185. }
  186. }
  187. namespace ScriptCanvas
  188. {
  189. AZStd::string FileLoadResult::ToString() const
  190. {
  191. if (m_isSuccess)
  192. {
  193. return "Success";
  194. }
  195. else
  196. {
  197. return AZStd::string::format("Failure@@@ File Read: %s@@@Deserialize: %s@@@Json: %s",
  198. m_fileReadErrors.c_str(), m_deserializeResult.m_errors.c_str(), m_deserializeResult.m_jsonResults.c_str());
  199. }
  200. }
  201. AZ::Outcome<SourceTree, AZStd::string> LoadEditorAssetTree(
  202. SourceHandle sourceHandle, MakeInternalGraphEntitiesUnique makeUniqueEntities)
  203. {
  204. using namespace ScriptCanvasFileHandlingCpp;
  205. SourceTreeLoader result;
  206. result.m_source = sourceHandle;
  207. auto loadOutome = LoadEditorAssetTree(result, makeUniqueEntities);
  208. if (loadOutome.IsSuccess())
  209. {
  210. return AZ::Success(result.ConvertToSourceTree());
  211. }
  212. else
  213. {
  214. return AZ::Failure(loadOutome.TakeError());
  215. }
  216. }
  217. FileLoadResult LoadFromFile
  218. ( AZStd::string_view path
  219. , MakeInternalGraphEntitiesUnique makeEntityIdsUnique
  220. , LoadReferencedAssets loadReferencedAssets)
  221. {
  222. namespace JSRU = AZ::JsonSerializationUtils;
  223. FileLoadResult result;
  224. auto fileStringOutcome = AZ::Utils::ReadFile<AZStd::string>(path);
  225. if (!fileStringOutcome)
  226. {
  227. result.m_isSuccess = false;
  228. result.m_fileReadErrors = fileStringOutcome.TakeError();
  229. return result;
  230. }
  231. const auto& asString = fileStringOutcome.GetValue();
  232. result.m_deserializeResult = Deserialize(asString, makeEntityIdsUnique, loadReferencedAssets);
  233. result.m_isSuccess = result.m_deserializeResult;
  234. if (!result.m_deserializeResult.m_isSuccessful)
  235. {
  236. result.m_fileReadErrors = "Script Canvas Graph Deserialization Failed - " + result.m_deserializeResult.m_errors + "\n";
  237. }
  238. const auto& graphDataPtr = result.m_deserializeResult.m_graphDataPtr;
  239. if (graphDataPtr && graphDataPtr->GetEditorGraph())
  240. {
  241. ScriptCanvasEditor::EditorGraphRequestBus::Event(
  242. graphDataPtr->GetEditorGraph()->GetScriptCanvasId(),
  243. &ScriptCanvasEditor::EditorGraphRequests::SetOriginalToNewIdsMap,
  244. result.m_deserializeResult.m_originalIdsToNewIds);
  245. }
  246. result.m_handle = SourceHandle::FromRelativePath(result.m_deserializeResult.m_graphDataPtr, path);
  247. return result;
  248. }
  249. }