public static unsafe Hash128 EnsureExistsFor(Hash128 sceneGUID, Hash128 buildConfigurationGUID) { var guid = ComputeBuildConfigurationGUID(sceneGUID, buildConfigurationGUID); if (s_BuildConfigurationCreated.Contains(guid)) { return(guid); } var guids = new SceneWithBuildConfigurationGUIDs { SceneGUID = sceneGUID, BuildConfiguration = buildConfigurationGUID }; var fileName = $"{k_SceneDependencyCachePath}/{guid}.sceneWithBuildSettings"; if (!File.Exists(fileName)) { Directory.CreateDirectory(k_SceneDependencyCachePath); using (var writer = new StreamBinaryWriter(fileName)) { writer.WriteBytes(&guids, sizeof(SceneWithBuildConfigurationGUIDs)); } File.WriteAllText(fileName + ".meta", $"fileFormatVersion: 2\nguid: {guid}\nDefaultImporter:\n externalObjects: {{}}\n userData:\n assetBundleName:\n assetBundleVariant:\n"); // Refresh is necessary because it appears the asset pipeline // can't depend on an asset on disk that has not yet been refreshed. AssetDatabase.Refresh(); } s_BuildConfigurationCreated.Add(guid); return(guid); }
public unsafe void SaveSources(NativeArray <BlobAssetReference <MeshSourceData> > sources, int surfaceId) { string path; if (surfaceId == -1) { path = GetGlobalPath(typeof(MeshSourceData).Name); } else { path = GetPath(surfaceId, typeof(MeshSourceData).Name, null); } using (StreamBinaryWriter writer = new StreamBinaryWriter(path)) { writer.Write(sources.Length); for (int i = 0; i < sources.Length; i++) { ref var source = ref sources[i].Value; int sizeInBytes = source.Indices.Length * UnsafeUtility.SizeOf <int>(); writer.Write(sizeInBytes); writer.WriteBytes(source.Indices.GetUnsafePtr(), sizeInBytes); sizeInBytes = source.Vertices.Length * UnsafeUtility.SizeOf <float3>(); writer.Write(sizeInBytes); writer.WriteBytes(source.Vertices.GetUnsafePtr(), sizeInBytes); } }
protected override void OnUpdate() { if (Input.GetKeyDown(KeyCode.H)) { Debug.Log($"Saving world..."); using (var writer = new StreamBinaryWriter(FullPath)) { EntityManager.CompleteAllJobs(); var q = EntityManager.CreateEntityQuery(typeof(Terminal)); EntityManager.DestroyEntity(q); SerializeUtilityHybrid.Serialize(EntityManager, writer, out _refs); int refCount = _refs == null ? 0 : _refs.Array.Length; Debug.Log($"RefCount: {refCount}"); } } if (Input.GetKeyDown(KeyCode.L)) { Debug.Log("Loading World..."); var loadWorld = new World("Loading World"); var em = loadWorld.EntityManager; using (var reader = new StreamBinaryReader(FullPath)) { SerializeUtilityHybrid.Deserialize(em, reader, _refs); } EntityManager.CompleteAllJobs(); EntityManager.DestroyEntity(EntityManager.UniversalQuery); EntityManager.MoveEntitiesFrom(em); loadWorld.Dispose(); } }
static int WriteEntityScene(EntityManager scene, Hash128 sceneGUID, string subsection, GameObjectConversionSettings settings, out int objectReferenceCount, NativeArray <EntityRemapUtility.EntityRemapInfo> entityRemapInfos = default) { k_ProfileEntitiesSceneSave.Begin(); var ctx = settings.AssetImportContext; var entitiesBinaryPath = GetSceneWritePath(sceneGUID, EntityScenesPaths.PathType.EntitiesBinary, subsection, ctx); var objRefsPath = GetSceneWritePath(sceneGUID, EntityScenesPaths.PathType.EntitiesUnityObjectReferences, subsection, ctx); ReferencedUnityObjects objRefs; objectReferenceCount = 0; EnsureFileIsWritableOrThrow(entitiesBinaryPath, ctx); // Write binary entity file int entitySceneFileSize = 0; using (var writer = new StreamBinaryWriter(entitiesBinaryPath)) { if (entityRemapInfos.IsCreated) { SerializeUtilityHybrid.Serialize(scene, writer, out objRefs, entityRemapInfos); } else { SerializeUtilityHybrid.Serialize(scene, writer, out objRefs); } entitySceneFileSize = (int)writer.Length; // Write object references k_ProfileEntitiesSceneWriteObjRefs.Begin(); if (objRefs != null) { var serializedObjectArray = new List <UnityObject>(); serializedObjectArray.Add(objRefs); for (int i = 0; i != objRefs.Array.Length; i++) { var obj = objRefs.Array[i]; if (obj != null && !EditorUtility.IsPersistent(obj)) { var saveInBuild = (obj.hideFlags & HideFlags.DontSaveInBuild) == 0; if (saveInBuild) { serializedObjectArray.Add(obj); } else { objRefs.Array[i] = null; } } } UnityEditorInternal.InternalEditorUtility.SaveToSerializedFileAndForget(serializedObjectArray.ToArray(), objRefsPath, false); objectReferenceCount = objRefs.Array.Length; } k_ProfileEntitiesSceneWriteObjRefs.End(); } k_ProfileEntitiesSceneSave.End(); return(entitySceneFileSize); }
// index -1 means 'use current index' public static void WriteContainerToDisk(this PersistentSceneSystem persistentSceneSystem, Hash128 containerIdentifier, bool initial = false, int index = -1) { Debug.Assert(initial == (index != -1), "Don't fill in an index if you want the initial container!"); // Path string path = CalculateStreamingAssetsPath(containerIdentifier); string folderPath = Path.GetDirectoryName(path); Debug.Assert(!string.IsNullOrEmpty(folderPath)); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // Container PersistentDataStorage dataStorage = persistentSceneSystem.PersistentDataStorage; PersistentDataContainer container; if (index == -1) { container = dataStorage.GetReadContainerForCurrentIndex(containerIdentifier); } else if (initial) { container = dataStorage.GetInitialStateReadContainer(containerIdentifier); } else { int oldIndex = dataStorage.NonWrappedIndex; dataStorage.ToIndex(index); container = dataStorage.GetReadContainerForCurrentIndex(containerIdentifier); dataStorage.ToIndex(oldIndex); } // Workaround for bug where AsyncReadManager.Read keeps a handle to the last 11 reads for (int i = 0; i < 12; i++) { string bugWorkaroundFilePath = Application.streamingAssetsPath + $"/UnityAsyncReadBugWorkaround{i.ToString()}.txt"; unsafe { var readCmd = new ReadCommand { Size = 0, Offset = 0, Buffer = null }; var readHandle = AsyncReadManager.Read(bugWorkaroundFilePath, &readCmd, 1); readHandle.JobHandle.Complete(); readHandle.Dispose(); } } // Write To Disk using (var fileStream = new StreamBinaryWriter(path)) { fileStream.Write(container.CalculateEntityCapacity()); NativeArray <byte> rawData = container.GetRawData(); fileStream.Write(rawData.Length); fileStream.WriteArray(rawData); } }
protected RecordableMatch(MatchConfig config, World world = null) : base(config, world) { ReplayFilePath = GetReplayFilename(); var binaryWriter = new StreamBinaryWriter(ReplayFilePath); _writer = new ReplayWriter(config, binaryWriter); // FIXME: This should write the MatchConfig here. }
static int WriteEntityScene(EntityManager scene, Entities.Hash128 sceneGUID, string subsection, NativeArray <EntityRemapUtility.EntityRemapInfo> entityRemapInfos = default(NativeArray <EntityRemapUtility.EntityRemapInfo>)) { k_ProfileEntitiesSceneSave.Begin(); var entitiesBinaryPath = EntityScenesPaths.GetPathAndCreateDirectory(sceneGUID, EntityScenesPaths.PathType.EntitiesBinary, subsection); var sharedDataPath = EntityScenesPaths.GetPathAndCreateDirectory(sceneGUID, EntityScenesPaths.PathType.EntitiesSharedComponents, subsection); GameObject sharedComponents; // We're going to do file writing manually, so make sure to do version control dance if needed if (Provider.isActive && !AssetDatabase.IsOpenForEdit(entitiesBinaryPath, StatusQueryOptions.UseCachedIfPossible)) { var task = Provider.Checkout(entitiesBinaryPath, CheckoutMode.Asset); task.Wait(); if (!task.success) { throw new System.Exception($"Failed to checkout entity cache file {entitiesBinaryPath}"); } } // Write binary entity file int entitySceneFileSize = 0; using (var writer = new StreamBinaryWriter(entitiesBinaryPath)) { if (entityRemapInfos.IsCreated) { SerializeUtilityHybrid.Serialize(scene, writer, out sharedComponents, entityRemapInfos); } else { SerializeUtilityHybrid.Serialize(scene, writer, out sharedComponents); } entitySceneFileSize = (int)writer.Length; } // Write shared component data prefab k_ProfileEntitiesSceneCreatePrefab.Begin(); //var oldPrefab = AssetDatabase.LoadMainAssetAtPath(sharedDataPath); //if (oldPrefab == null) // PrefabUtility.CreatePrefab(sharedDataPath, sharedComponents, ReplacePrefabOptions.ReplaceNameBased); if (sharedComponents != null) { PrefabUtility.SaveAsPrefabAsset(sharedComponents, sharedDataPath); } //else // PrefabUtility.Save //PrefabUtility.ReplacePrefab(sharedComponents, oldPrefab, ReplacePrefabOptions.ReplaceNameBased); Object.DestroyImmediate(sharedComponents); k_ProfileEntitiesSceneCreatePrefab.End(); k_ProfileEntitiesSceneSave.End(); return(entitySceneFileSize); }
/// <summary> /// Writes the blob data to a path with serialized version. /// </summary> /// <param name="builder">The BlobBuilder containing the blob to write.</param> /// <param name="path">The path to write the blob data.</param> /// <param name="version">Serialized version number of the blob data.</param> public static void Write(BlobBuilder builder, string path, int verison) { using (var asset = builder.CreateBlobAssetReference <T>(Allocator.TempJob)) using (var writer = new StreamBinaryWriter(path)) { writer.Write(verison); writer.Write(asset); } }
public Task InitializeAsync(IVostokHostingEnvironment environment) { SetupEventsLimitMetric(environment, () => environment.ConfigurationProvider.Get <AggregatorSettings>().EventsLimitMetric); var settings = environment.ConfigurationProvider.Get <AggregatorSettings>(); Func <string> apiKeyProvider = () => environment.SecretConfigurationProvider.Get <AggregatorSecretSettings>().HerculesApiKey; var binaryWriterSettings = new StreamBinaryWriterSettings( apiKeyProvider, new AdHocClusterProvider(() => null)) { MetricContext = environment.Metrics.Instance, GateClientAdditionalSetup = environment.HostExtensions.Get <ClusterClientSetup>(Constants.GateClientSetupKey) }; var binaryWriter = new StreamBinaryWriter(binaryWriterSettings, environment.Log); var eventsWriterSettings = new StreamBinaryEventsWriterSettings(binaryWriter, settings.TargetStream) { BufferCapacityLimit = settings.EventsWriteBufferCapacityLimit }; var eventsWriter = new StreamBinaryEventsWriter(eventsWriterSettings, environment.Log); var consumerSettings = new WindowedStreamConsumerSettings <MetricEvent, MetricTags>( settings.SourceStream, apiKeyProvider, new AdHocClusterProvider(() => null), s => s.Tags, s => s.Timestamp, _ => new MetricProcessor(environment.HostExtensions.Get <Func <IAggregateFunction> >(Constants.AggregateFunctionKey)(), eventsWriter), r => new HerculesMetricEventReader(r), environment.HostExtensions.Get <IStreamCoordinatesStorage>(Constants.LeftCoordinatesStorageKey), environment.HostExtensions.Get <IStreamCoordinatesStorage>(Constants.RightCoordinatesStorageKey), () => new StreamShardingSettings(environment.ApplicationReplicationInfo.InstanceIndex, environment.ApplicationReplicationInfo.InstancesCount) ) { EventsReadBatchSize = settings.EventsReadBatchSize, Lag = settings.Lag, Period = settings.Period, LagProvider = e => e.AggregationParameters?.GetAggregationLag(), PeriodProvider = e => e.AggregationParameters?.GetAggregationPeriod(), MetricContext = environment.Metrics.Instance, StreamApiClientAdditionalSetup = environment.HostExtensions.Get <ClusterClientSetup>(Constants.StreamClientSetupKey), MaximumDeltaAfterNow = settings.MaximumDeltaAfterNow, OnBatchBegin = _ => writeTask?.GetAwaiter().GetResult(), OnBatchEnd = _ => { writeTask = eventsWriter.WriteAsync().SilentlyContinue(); } }; consumer = new WindowedStreamConsumer <MetricEvent, MetricTags>(consumerSettings, environment.Log); return(Task.CompletedTask); }
static unsafe void WriteEditorLiveLinkCacheGUID() { Directory.CreateDirectory(k_LiveLinkEditorCacheDir); using (var stream = new StreamBinaryWriter(k_LiveLinkEditorCacheGUIDPath)) { Hash128 guid = s_CacheGUID; stream.WriteBytes(&guid, sizeof(Hash128)); } }
public static unsafe void WriteBootstrap(string path, Hash128 buildConfigurationGUID) { long handshakeId = GetEditorLiveLinkId(); using (var stream = new StreamBinaryWriter(path)) { stream.WriteBytes(&buildConfigurationGUID, sizeof(Hash128)); stream.WriteBytes(&handshakeId, sizeof(long)); } }
//TODO: There is too much code duplication here, refactor this to receive general artifacts from the editor unsafe void ReceiveSubSceneRefGUIDs(MessageEventArgs args) { fixed(byte *ptr = args.data) { var reader = new UnsafeAppendBuffer.Reader(ptr, args.data.Length); var subSceneAsset = reader.ReadNext <ResolvedSubSceneID>(); var sectionIndex = reader.ReadNext <int>(); reader.ReadNext(out NativeArray <RuntimeGlobalObjectId> objRefGUIDs, Allocator.Persistent); var refObjGUIDsPath = EntityScenesPaths.GetLiveLinkCachePath(subSceneAsset.TargetHash, EntityScenesPaths.PathType.EntitiesUnityObjectReferences, sectionIndex); // Not printing error because this can happen when running the same player multiple times on the same machine if (File.Exists(refObjGUIDsPath)) { LiveLinkMsg.LogInfo($"Received {subSceneAsset.SubSceneGUID} | {subSceneAsset.TargetHash} but it already exists on disk"); } else { LiveLinkMsg.LogInfo($"ReceieveSubSceneRefGUIDs => {subSceneAsset.SubSceneGUID} | {subSceneAsset.TargetHash},"); var tempCachePath = GetTempCachePath(); using (var writer = new StreamBinaryWriter(tempCachePath)) { writer.Write(objRefGUIDs.Length); writer.WriteArray(objRefGUIDs); } try { File.Move(tempCachePath, refObjGUIDsPath); } catch (Exception e) { File.Delete(tempCachePath); if (!File.Exists(refObjGUIDsPath)) { Debug.LogError($"Failed to move temporary file. Exception: {e.Message}"); LiveLinkMsg.LogInfo($"Failed to move temporary file. Exception: {e.Message}"); } } } if (!_WaitingForSubScenes.ContainsKey(subSceneAsset.SubSceneGUID)) { Debug.LogError($"Received {subSceneAsset.SubSceneGUID} | {subSceneAsset.TargetHash} without requesting it"); LiveLinkMsg.LogInfo($"Received {subSceneAsset.SubSceneGUID} | {subSceneAsset.TargetHash} without requesting it"); return; } var waitingSubScene = _WaitingForSubScenes[subSceneAsset.SubSceneGUID]; waitingSubScene.SubSections.Add(objRefGUIDs); _WaitingForSubScenes[subSceneAsset.SubSceneGUID] = waitingSubScene; } }
public static unsafe void WritePlayerLiveLinkCacheGUID() { CreatePlayerLiveLinkCacheDir(); var cacheGUIDPath = $"{EntityScenesPaths.GetLiveLinkCacheDirPath()}/livelinkcacheguid"; using (var stream = new StreamBinaryWriter(cacheGUIDPath)) { Hash128 guid = LiveLinkCacheGUID; stream.WriteBytes(&guid, sizeof(Hash128)); } }
private static unsafe void WriteSceneWithBuildSettings(ref Hash128 guid, ref SceneWithBuildConfigurationGUIDs sceneWithBuildConfigurationGUIDs, string path) { Directory.CreateDirectory(k_SceneDependencyCachePath); using (var writer = new StreamBinaryWriter(path)) { fixed(void *vp = &sceneWithBuildConfigurationGUIDs) { writer.WriteBytes(vp, sizeof(SceneWithBuildConfigurationGUIDs)); } } File.WriteAllText(path + ".meta", $"fileFormatVersion: 2\nguid: {guid}\nDefaultImporter:\n externalObjects: {{}}\n userData:\n assetBundleName:\n assetBundleVariant:\n"); }
static void SaveWorld(EntityManager entityManager, out object[] objectTable) { string filePath = Application.persistentDataPath + "/test.bin"; if (File.Exists(filePath)) { File.Delete(filePath); } using (var binaryWriter = new StreamBinaryWriter(filePath)) { SerializeUtility.SerializeWorld(entityManager, binaryWriter, out objectTable); } }
static void SaveHybrid(EntityManager entityManager, out ReferencedUnityObjects objectTable) { string filePath = Application.persistentDataPath + "/testHyb.bin"; if (File.Exists(filePath)) { File.Delete(filePath); } using (var binaryWriter = new StreamBinaryWriter(filePath)) { SerializeUtilityHybrid.Serialize(entityManager, binaryWriter, out objectTable); } }
static int WriteEntityScene(EntityManager scene, Entities.Hash128 sceneGUID, string subsection, NativeArray <EntityRemapUtility.EntityRemapInfo> entityRemapInfos = default(NativeArray <EntityRemapUtility.EntityRemapInfo>)) { k_ProfileEntitiesSceneSave.Begin(); var entitiesBinaryPath = EntityScenesPaths.GetPathAndCreateDirectory(sceneGUID, EntityScenesPaths.PathType.EntitiesBinary, subsection); var sharedDataPath = EntityScenesPaths.GetPathAndCreateDirectory(sceneGUID, EntityScenesPaths.PathType.EntitiesSharedComponents, subsection); GameObject sharedComponents; // Write binary entity file int entitySceneFileSize = 0; using (var writer = new StreamBinaryWriter(entitiesBinaryPath)) { if (entityRemapInfos.IsCreated) { SerializeUtilityHybrid.Serialize(scene, writer, out sharedComponents, entityRemapInfos); } else { SerializeUtilityHybrid.Serialize(scene, writer, out sharedComponents); } entitySceneFileSize = (int)writer.Length; } // Write shared component data prefab k_ProfileEntitiesSceneCreatePrefab.Begin(); //var oldPrefab = AssetDatabase.LoadMainAssetAtPath(sharedDataPath); //if (oldPrefab == null) // PrefabUtility.CreatePrefab(sharedDataPath, sharedComponents, ReplacePrefabOptions.ReplaceNameBased); if (sharedComponents != null) { PrefabUtility.SaveAsPrefabAsset(sharedComponents, sharedDataPath); } //else // PrefabUtility.Save //PrefabUtility.ReplacePrefab(sharedComponents, oldPrefab, ReplacePrefabOptions.ReplaceNameBased); Object.DestroyImmediate(sharedComponents); k_ProfileEntitiesSceneCreatePrefab.End(); k_ProfileEntitiesSceneSave.End(); return(entitySceneFileSize); }
private static unsafe void WriteEntitySceneWithBuildConfig(Hash128 guid, SceneWithBuildConfigurationGUIDs sceneWithBuildConfigurationGUIDs, string path) { var previousPath = AssetDatabaseCompatibility.GuidToPath(guid); if (!string.IsNullOrEmpty(previousPath) && previousPath != path) { UnityEngine.Debug.LogError($"EntitySceneWithBuildConfig guid is not unique {guid}. ScenePath: '{AssetDatabaseCompatibility.GuidToPath(sceneWithBuildConfigurationGUIDs.SceneGUID)}' Conflicting GUID: '{previousPath}'"); } Directory.CreateDirectory(k_SceneDependencyCachePath); using (var writer = new StreamBinaryWriter(path)) { writer.WriteBytes(&sceneWithBuildConfigurationGUIDs, sizeof(SceneWithBuildConfigurationGUIDs)); } File.WriteAllText(path + ".meta", $"fileFormatVersion: 2\nguid: {guid}\nDefaultImporter:\n externalObjects: {{}}\n userData:\n assetBundleName:\n assetBundleVariant:\n"); }
private static unsafe void WriteSceneWithBuildSettings(ref Hash128 guid, ref SceneWithBuildConfigurationGUIDs sceneWithBuildConfigurationGUIDs, string path) { Directory.CreateDirectory(k_SceneDependencyCachePath); using (var writer = new StreamBinaryWriter(path)) { fixed(void *vp = &sceneWithBuildConfigurationGUIDs) { writer.WriteBytes(vp, sizeof(SceneWithBuildConfigurationGUIDs)); } } File.WriteAllText(path + ".meta", $"fileFormatVersion: 2\nguid: {guid}\nDefaultImporter:\n externalObjects: {{}}\n userData:\n assetBundleName:\n assetBundleVariant:\n"); // Refresh is necessary because it appears the asset pipeline // can't depend on an asset on disk that has not yet been refreshed. AssetDatabase.Refresh(); }
public unsafe bool SaveTiles(Dictionary <int2, NavMeshTile> tiles, int surfaceId) { string path = GetPath(surfaceId, typeof(NavMeshTile).Name, null); using (StreamBinaryWriter writer = new StreamBinaryWriter(path)) { writer.Write(tiles.Count); foreach (NavMeshTile tile in tiles.Values) { writer.Write(tile.Data.Length); fixed(void *dataPtr = tile.Data) { writer.WriteBytes(dataPtr, tile.Data.Length); } } } return(true); }
private static string DoWriteArtifact <TAction>(string artifactFile, BlobAssetReference <ActionGraph <TAction> > blobAssetReference) where TAction : Delegate { using var writer = new StreamBinaryWriter(artifactFile); writer.Write(blobAssetReference); AssetDatabase.ImportAsset(artifactFile); #if ADDRESSABLES_EXISTS var guid = AssetDatabase.GUIDFromAssetPath(artifactFile).ToString(); if (AddressableAssetSettingsDefaultObject.SettingsExists) { var settings = AddressableAssetSettingsDefaultObject.Settings; if (settings != null) { var group = settings.DefaultGroup; var entry = settings.CreateOrMoveEntry(guid, group, true, true); } } return(guid); #else return(AssetDatabase.GUIDFromAssetPath(artifactFile).ToString()); #endif }
private void SaveData() { if (!Directory.Exists("Saves")) { Directory.CreateDirectory("Saves"); } var formatter = new BinaryFormatter(); var objects = new List <System.Object>(); var saveFile = File.Create("Saves/Save.bin"); // DOTS Save world if (World.All.Count < 1) { return; } using (var writer = new StreamWriter(yamlpath)) { // Path for saving world var binaryWorldPath = _FileLocation + "\\" + "DefaultWorld.world"; // path backslash for system access var binaryWriter = new StreamBinaryWriter(binaryWorldPath); // Save whole world // not hybrid SerializeUtility.SerializeWorld(em, binaryWriter, out var objectReferences); var referencedObjectsPath = "Assets/ReferencedUnityWorldObjects.asset"; // path forward slash for asset access SerializeUtilityHybrid.Serialize(em, binaryWriter, out ReferencedUnityObjects objectReferences); binaryWriter.Dispose(); // For debugging: log all referenced objects which are saved QueryReferences.Query(objectReferences); AssetDatabase.CreateAsset(objectReferences, referencedObjectsPath); objects.Add(objectReferences); /*var zx = GameObject.Find("test"); * var xm = zx.GetComponent<MeshFilter>(); * var m = xm.sharedMesh; * var code = m.GetHashCode();*/ } formatter.Serialize(saveFile, objects); }
public static void WriteRefGuids(List <ReferencedUnityObjects> referencedUnityObjects, AssetImportContext ctx) { for (var index = 0; index < referencedUnityObjects.Count; index++) { var objRefs = referencedUnityObjects[index]; if (objRefs == null) { continue; } var refGuidsPath = ctx.GetResultPath($"{index}.{EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesUnityObjectRefGuids)}"); var runtimeGlobalObjectIds = ReferencedUnityObjectsToRuntimeGlobalObjectIds(objRefs); using (var refGuidWriter = new StreamBinaryWriter(refGuidsPath)) { refGuidWriter.Write(runtimeGlobalObjectIds.Length); refGuidWriter.WriteArray(runtimeGlobalObjectIds.AsArray()); } runtimeGlobalObjectIds.Dispose(); } }
/// <summary> /// Default save method. Saves world as binary file. /// </summary> /// <param name="debug"></param> public static void Save(bool debug = false) { if (World.All.Count < 1) { return; } var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; // Path for saving world var binaryWriter = new StreamBinaryWriter(WorldLocation); // Save whole world // pure version - SerializeUtility.SerializeWorld(em, binaryWriter, out var objectReferences); SerializeUtilityHybrid.Serialize(entityManager, binaryWriter, out var objectReferences); if (debug) { QueryReferences.Query(objectReferences); } AssetDatabase.CreateAsset(objectReferences, WorldReferencesLocation); Debug.Log("Saved"); }
static void WriteAssetDependencyGUIDs(List <ReferencedUnityObjects> referencedUnityObjects, SceneSectionData[] sectionData, AssetImportContext ctx) { for (var index = 0; index < referencedUnityObjects.Count; index++) { var sectionIndex = sectionData[index].SubSectionIndex; var objRefs = referencedUnityObjects[index]; if (objRefs == null) { continue; } var path = ctx.GetResultPath($"{sectionIndex}.{EntityScenesPaths.GetExtension(EntityScenesPaths.PathType.EntitiesAssetDependencyGUIDs)}"); var assetDependencyGUIDs = ReferencedUnityObjectsToGUIDs(objRefs, ctx); using (var writer = new StreamBinaryWriter(path)) { writer.Write(assetDependencyGUIDs.Length); writer.WriteArray(assetDependencyGUIDs.AsArray()); } assetDependencyGUIDs.Dispose(); } }
public static bool WriteWorldToFile(World world, FileInfo outputFile) { // TODO need to bring this back #if false // Check for missing assembly references var unresolvedComponentTypes = GetAllUsedComponentTypes(world).Where(t => !DomainCache.IsIncludedInProject(project, t.GetManagedType())).ToArray(); if (unresolvedComponentTypes.Length > 0) { foreach (var unresolvedComponentType in unresolvedComponentTypes) { var type = unresolvedComponentType.GetManagedType(); Debug.LogError($"Could not resolve component type '{type.FullName}' while exporting {scenePath.ToHyperLink()}. Are you missing an assembly reference to '{type.Assembly.GetName().Name}' ?"); } return(false); } #endif var directoryName = Path.GetDirectoryName(outputFile.FullName); if (string.IsNullOrEmpty(directoryName)) { throw new ArgumentException($"Invalid output file directory: {directoryName}", nameof(outputFile)); } if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // Merges the entities and shared component streams, (optionally) compresses them, and finally serializes to disk with a small header in front using (var fileStream = new StreamBinaryWriter(outputFile.FullName)) using (var entitiesWriter = new MemoryBinaryWriter()) { var entityRemapInfos = new NativeArray <EntityRemapUtility.EntityRemapInfo>(world.EntityManager.EntityCapacity, Allocator.Temp); SerializeUtility.SerializeWorldInternal(world.EntityManager, entitiesWriter, out var referencedObjects, entityRemapInfos, isDOTSRuntime: true); entityRemapInfos.Dispose(); if (referencedObjects != null) { throw new ArgumentException("We are serializing a world that contains UnityEngine.Object references which are not supported in Dots Runtime."); } #if TINY_SCENE_DEP unsafe { var worldHeader = new SceneHeader(); worldHeader.DecompressedSize = entitiesWriter.Length; worldHeader.Codec = Codec.LZ4; worldHeader.SerializeHeader(fileStream); if (worldHeader.Codec != Codec.None) { int compressedSize = CodecService.Compress(worldHeader.Codec, entitiesWriter.Data, entitiesWriter.Length, out var compressedData); fileStream.WriteBytes(compressedData, compressedSize); } else { fileStream.WriteBytes(entitiesWriter.Data, entitiesWriter.Length); } } #endif } return(true); }
private static bool ExportWorld(FileInfo outputFile, Project project, string scenePath, World world, bool performConversion = true) { if (performConversion) { SceneConversion.Convert(world); } // Null out any references to avoid the SerializeUtility from trying to patch asset entities. world.GetOrCreateSystem <ClearRemappedEntityReferenceSystem>().Update(); // Check for missing assembly references var unresolvedComponentTypes = GetAllUsedComponentTypes(world).Where(t => !DomainCache.IsIncludedInProject(project, t.GetManagedType())).ToArray(); if (unresolvedComponentTypes.Length > 0) { foreach (var unresolvedComponentType in unresolvedComponentTypes) { var type = unresolvedComponentType.GetManagedType(); Debug.LogError($"Could not resolve component type '{type.FullName}' while exporting {scenePath.HyperLink()}. Are you missing an assembly reference to '{type.Assembly.GetName().Name}' ?"); } return(false); } // Remove non-exported components var nonExportedComponentTypes = UnityEditor.TypeCache.GetTypesWithAttribute <NonExportedAttribute>().Select(t => new ComponentType(t)); world.EntityManager.RemoveComponent(world.EntityManager.UniversalQuery, new ComponentTypes(nonExportedComponentTypes.ToArray())); // Merges the entities and shared component streams, (optionally) compresses them, and finally serializes to disk with a small header in front using (var fileStream = new StreamBinaryWriter(outputFile.FullName)) using (var entitiesWriter = new MemoryBinaryWriter()) using (var sharedComponentWriter = new MemoryBinaryWriter()) using (var combinedDataWriter = new MemoryBinaryWriter()) { SerializeUtility.SerializeWorld(world.EntityManager, entitiesWriter, out var sharedComponentsToSerialize); if (sharedComponentsToSerialize.Length > 0) { SerializeUtility.SerializeSharedComponents(world.EntityManager, sharedComponentWriter, sharedComponentsToSerialize); } unsafe { combinedDataWriter.WriteBytes(sharedComponentWriter.Data, sharedComponentWriter.Length); combinedDataWriter.WriteBytes(entitiesWriter.Data, entitiesWriter.Length); var worldHeader = new SceneHeader(); worldHeader.SharedComponentCount = sharedComponentsToSerialize.Length; worldHeader.DecompressedSize = entitiesWriter.Length + sharedComponentWriter.Length; worldHeader.Codec = Codec.LZ4; worldHeader.SerializeHeader(fileStream); if (worldHeader.Codec != Codec.None) { int compressedSize = CodecService.Compress(worldHeader.Codec, combinedDataWriter.Data, combinedDataWriter.Length, out var compressedData); fileStream.WriteBytes(compressedData, compressedSize); } else { fileStream.WriteBytes(combinedDataWriter.Data, combinedDataWriter.Length); } } } return(true); }