コード例 #1
0
        public override void Serialize(ref Sound obj, ArchiveMode mode, SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services    = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var audioEngine = services.GetServiceAs <IAudioEngineProvider>()?.AudioEngine;

                obj.CompressedDataUrl = stream.ReadString();
                obj.SampleRate        = stream.ReadInt32();
                obj.Channels          = stream.ReadByte();
                obj.StreamFromDisk    = stream.ReadBoolean();
                obj.Spatialized       = stream.ReadBoolean();
                obj.NumberOfPackets   = stream.ReadInt16();
                obj.MaxPacketLength   = stream.ReadInt16();

                if (!obj.StreamFromDisk && audioEngine != null && audioEngine.State != AudioEngineState.Invalidated && audioEngine.State != AudioEngineState.Disposed) //immediatelly preload all the data and decode
                {
                    using (var soundStream = ContentManager.FileProvider.OpenStream(obj.CompressedDataUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable))
                        using (var decoder = new Celt(obj.SampleRate, CompressedSoundSource.SamplesPerFrame, obj.Channels, true))
                        {
                            var reader           = new BinarySerializationReader(soundStream);
                            var samplesPerPacket = CompressedSoundSource.SamplesPerFrame * obj.Channels;

                            obj.PreloadedBuffer = AudioLayer.BufferCreate(samplesPerPacket * obj.NumberOfPackets * sizeof(short));

                            var memory = new UnmanagedArray <short>(samplesPerPacket * obj.NumberOfPackets);

                            var offset       = 0;
                            var outputBuffer = new short[samplesPerPacket];
                            for (var i = 0; i < obj.NumberOfPackets; i++)
                            {
                                var len = reader.ReadInt16();
                                var compressedBuffer = reader.ReadBytes(len);
                                var samplesDecoded   = decoder.Decode(compressedBuffer, len, outputBuffer);
                                memory.Write(outputBuffer, offset, 0, samplesDecoded * obj.Channels);
                                offset += samplesDecoded * obj.Channels * sizeof(short);
                            }

                            AudioLayer.BufferFill(obj.PreloadedBuffer, memory.Pointer, memory.Length * sizeof(short), obj.SampleRate, obj.Channels == 1);
                            memory.Dispose();
                        }
                }

                if (audioEngine != null)
                {
                    obj.Attach(audioEngine);
                }
            }
            else
            {
                stream.Write(obj.CompressedDataUrl);
                stream.Write(obj.SampleRate);
                stream.Write((byte)obj.Channels);
                stream.Write(obj.StreamFromDisk);
                stream.Write(obj.Spatialized);
                stream.Write((short)obj.NumberOfPackets);
                stream.Write((short)obj.MaxPacketLength);
            }
        }
コード例 #2
0
        public override void Serialize(ContentSerializerContext context, SerializationStream stream, Image textureData)
        {
            if (context.Mode == ArchiveMode.Deserialize)
            {
                var isStreamable = stream.ReadBoolean();
                if (!isStreamable)
                {
                    var image = Image.Load(stream.NativeStream);
                    textureData.InitializeFrom(image);
                }
                else
                {
                    // Read image header
                    var imageDescription = new ImageDescription();
                    ImageHelper.ImageDescriptionSerializer.Serialize(ref imageDescription, ArchiveMode.Deserialize, stream);

                    // Read content storage header
                    ContentStorageHeader storageHeader;
                    ContentStorageHeader.Read(stream, out storageHeader);

                    // Deserialize whole texture to image without streaming feature
                    var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);
                    DeserializeImage(contentSerializerContext.ContentManager, textureData, ref imageDescription, ref storageHeader);
                }
            }
            else
            {
                textureData.Save(stream.NativeStream, ImageFileType.Xenko);
            }
        }
コード例 #3
0
 public override void Serialize(ref ObjectId obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         var hasId = obj != Empty;
         stream.Write(hasId);
         if (hasId)
         {
             fixed(uint *hash = &obj.hash1)
             stream.Serialize((IntPtr)hash, HashSize);
         }
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         var hasId = stream.ReadBoolean();
         if (hasId)
         {
             var id = new byte[HashSize];
             stream.Serialize(id, 0, HashSize);
             obj = new ObjectId(id);
         }
         else
         {
             obj = ObjectId.Empty;
         }
     }
 }
コード例 #4
0
ファイル: CloneSerializer.cs プロジェクト: yongweisun/paradox
        public override void PreSerialize(ref T obj, ArchiveMode mode, SerializationStream stream)
        {
            var cloneContext = stream.Context.Get(EntityCloner.CloneContextProperty);

            if (mode == ArchiveMode.Serialize)
            {
                // Check against list of items that should be included in the stream (Entity and EntityComponent whose parent is the cloned Entity).
                // First try MappedObjects, then ClonedObjects.
                object mappedObject   = null;
                bool   isSharedObject = cloneContext.MappedObjects != null && cloneContext.MappedObjects(obj, out mappedObject);

                if (!isSharedObject && cloneContext.ClonedObjects != null && !cloneContext.ClonedObjects.Contains(obj))
                {
                    isSharedObject = true;
                    mappedObject   = obj;
                }

                stream.Write(isSharedObject);

                if (isSharedObject)
                {
                    stream.Write(cloneContext.SharedObjects.Count);
                    cloneContext.SharedObjects.Add(mappedObject);
                }
                else
                {
                    cloneContext.SerializedObjects.Add(obj);
                }
            }
            else
            {
                bool isSharedObject = stream.ReadBoolean();

                if (isSharedObject)
                {
                    var sharedObjectIndex = stream.ReadInt32();
                    obj = (T)cloneContext.SharedObjects[sharedObjectIndex];

                    // TODO: Hardcoded
                    // Model need to be cloned
                    if (obj is Model)
                    {
                        obj = (T)(object)((Model)(object)obj).Instantiate();
                    }
                }
                else
                {
                    base.PreSerialize(ref obj, mode, stream);
                    cloneContext.SerializedObjects.Add(obj);
                }
            }
        }
コード例 #5
0
        public override void Serialize(ref Sound obj, ArchiveMode mode, SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services    = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var audioEngine = services.GetService <IAudioEngineProvider>()?.AudioEngine;

                obj.FileProvider      = services.GetService <IDatabaseFileProviderService>()?.FileProvider;
                obj.CompressedDataUrl = stream.ReadString();
                obj.SampleRate        = stream.ReadInt32();
                obj.Channels          = stream.ReadByte();
                obj.StreamFromDisk    = stream.ReadBoolean();
                obj.Spatialized       = stream.ReadBoolean();
                obj.NumberOfPackets   = stream.ReadInt32();
                obj.MaxPacketLength   = stream.ReadInt16();
                obj.Samples           = stream.ReadInt32();

                if (!obj.StreamFromDisk && audioEngine != null && audioEngine.State != AudioEngineState.Invalidated && audioEngine.State != AudioEngineState.Disposed) //immediatelly preload all the data and decode
                {
                    obj.LoadSoundInMemory();
                }

                if (audioEngine != null)
                {
                    obj.Attach(audioEngine);
                }
            }
            else
            {
                stream.Write(obj.CompressedDataUrl);
                stream.Write(obj.SampleRate);
                stream.Write((byte)obj.Channels);
                stream.Write(obj.StreamFromDisk);
                stream.Write(obj.Spatialized);
                stream.Write(obj.NumberOfPackets);
                stream.Write((short)obj.MaxPacketLength);
                stream.Write(obj.Samples);
            }
        }
コード例 #6
0
            public override void Serialize(ref IndexBufferBinding indexBufferBinding, ArchiveMode mode, SerializationStream stream)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    var buffer  = stream.Read <Buffer>();
                    var is32Bit = stream.ReadBoolean();
                    var count   = stream.ReadInt32();
                    var offset  = stream.ReadInt32();

                    indexBufferBinding = new IndexBufferBinding(buffer, is32Bit, count, offset);
                }
                else
                {
                    stream.Write(indexBufferBinding.Buffer);
                    stream.Write(indexBufferBinding.Is32Bit);
                    stream.Write(indexBufferBinding.Count);
                    stream.Write(indexBufferBinding.Offset);
                }
            }
コード例 #7
0
 public override void Serialize(ref ServiceSyncInfo info, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(info.CompressionThreshold);
         stream.Write(info.ServiceKeyIndex);
         stream.Write(info.UseCompression);
         stream.Write(info.MethodInfos.Length);
         foreach (var method in info.MethodInfos)
         {
             stream.Write(method.MethodIdent);
             stream.Write(method.MethodName);
             stream.Write(method.MethodReturnType);
             stream.Write(method.ParameterTypes.Length);
             foreach (var paramType in method.ParameterTypes)
             {
                 stream.Write(paramType);
             }
         }
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         info.CompressionThreshold = stream.ReadInt32();
         info.ServiceKeyIndex      = stream.ReadInt32();
         info.UseCompression       = stream.ReadBoolean();
         var length = stream.ReadInt32();
         info.MethodInfos = new MethodSyncInfo[length];
         for (int i = 0; i < length; i++)
         {
             info.MethodInfos[i]                  = new MethodSyncInfo();
             info.MethodInfos[i].MethodIdent      = stream.ReadInt32();
             info.MethodInfos[i].MethodName       = stream.ReadString();
             info.MethodInfos[i].MethodReturnType = stream.ReadString();
             var paramLength = stream.ReadInt32();
             info.MethodInfos[i].ParameterTypes = new string[paramLength];
             for (int j = 0; j < paramLength; j++)
             {
                 info.MethodInfos[i].ParameterTypes[j] = stream.ReadString();
             }
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// Reads header instance from a stream.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="result">Result data</param>
        public static void Read(SerializationStream stream, out ContentStorageHeader result)
        {
            result = new ContentStorageHeader();
            var version = stream.ReadInt32();

            if (version == 1)
            {
                result.InitialImage = stream.ReadBoolean();
                result.DataUrl      = stream.ReadString();
                result.PackageTime  = new DateTime(stream.ReadInt64());
                int chunksCount = stream.ReadInt32();
                result.Chunks = new ChunkEntry[chunksCount];
                for (int i = 0; i < chunksCount; i++)
                {
                    result.Chunks[i].Location = stream.ReadInt32();
                    result.Chunks[i].Size     = stream.ReadInt32();
                }
                result.HashCode = stream.ReadInt32();

                return;
            }

            throw new SerializationException($"Invald {nameof(ContentStorageHeader)} version.");
        }
コード例 #9
0
        internal static void Serialize(ArchiveMode mode, SerializationStream stream, Texture texture, bool allowContentStreaming)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var graphicsDeviceService     = services.GetSafeServiceAs <IGraphicsDeviceService>();
                var texturesStreamingProvider = services.GetService <ITexturesStreamingProvider>();

                var isStreamable = stream.ReadBoolean();
                if (!isStreamable)
                {
                    texturesStreamingProvider?.UnregisterTexture(texture);

                    // TODO: Error handling?
                    using (var textureData = Image.Load(stream.NativeStream))
                    {
                        if (texture.GraphicsDevice != null)
                        {
                            texture.OnDestroyed(); //Allows fast reloading todo review maybe?
                        }
                        texture.AttachToGraphicsDevice(graphicsDeviceService.GraphicsDevice);
                        texture.InitializeFrom(textureData.Description, new TextureViewDescription(), textureData.ToDataBox());

                        // Setup reload callback (reload from asset manager)
                        var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);
                        if (contentSerializerContext != null)
                        {
                            var assetManager = contentSerializerContext.ContentManager;
                            var url          = contentSerializerContext.Url;

                            texture.Reload = (graphicsResource) =>
                            {
                                var textureDataReloaded = assetManager.Load <Image>(url);
                                ((Texture)graphicsResource).Recreate(textureDataReloaded.ToDataBox());
                                assetManager.Unload(textureDataReloaded);
                            };
                        }
                    }
                }
                else
                {
                    if (texture.GraphicsDevice != null)
                    {
                        texture.OnDestroyed();
                    }

                    texture.AttachToGraphicsDevice(graphicsDeviceService.GraphicsDevice);
                    texture.Reload = null;

                    // Read image header
                    var imageDescription = new ImageDescription();
                    ImageHelper.ImageDescriptionSerializer.Serialize(ref imageDescription, ArchiveMode.Deserialize, stream);

                    // Read content storage header
                    ContentStorageHeader storageHeader;
                    ContentStorageHeader.Read(stream, out storageHeader);

                    // Check if streaming service is available
                    if (texturesStreamingProvider != null)
                    {
                        // Load initial texture (with limited number of mipmaps)
                        if (storageHeader.InitialImage)
                        {
                            using (var textureData = Image.Load(stream.NativeStream))
                            {
                                if (texture.GraphicsDevice != null)
                                {
                                    texture.OnDestroyed(); //Allows fast reloading todo review maybe?
                                }
                                texture.InitializeFrom(textureData.Description, new TextureViewDescription(), textureData.ToDataBox());
                            }
                        }

                        if (allowContentStreaming)
                        {
                            // Register texture for streaming
                            // NOTE: Here we don't load texture data and don't allocate GPU memory
                            texturesStreamingProvider.RegisterTexture(texture, ref imageDescription, ref storageHeader);
                        }
                        else
                        {
                            // Request texture loading (should be fully loaded)
                            texturesStreamingProvider.FullyLoadTexture(texture, ref imageDescription, ref storageHeader);
                        }
                    }
                    else
                    {
                        // Load initial texture and discard it (we are going to load the full chunk texture right after)
                        if (storageHeader.InitialImage)
                        {
                            using (var textureData = Image.Load(stream.NativeStream)) { }
                        }

                        // Deserialize whole texture without streaming feature
                        var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);
                        DeserializeTexture(contentSerializerContext.ContentManager, texture, ref imageDescription, ref storageHeader);
                    }
                }
            }
            else
            {
                var textureData = texture.GetSerializationData();
                if (textureData is null)
                {
                    throw new InvalidOperationException("Trying to serialize a Texture without CPU info.");
                }

                textureData.Write(stream);
            }
        }
コード例 #10
0
        public override void Serialize(ref SongLibrary obj, ArchiveMode mode, [NotNull] SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services      = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var contentManger = services.GetService <IContentManager>();

                // load songs
                {
                    int idCount = stream.ReadInt32();
                    obj.songs = new Dictionary <Guid, Song>(idCount);

                    for (int i = 0; i < idCount; i++)
                    {
                        Guid id = new Guid();
                        guidSerializer.Serialize(ref id, mode, stream);

                        var songUrl = FormattableString.Invariant($"Songs/{id}");
                        var song    = contentManger.Get <Song>(songUrl) ?? contentManger.Load <Song>(songUrl);

                        if (song == null)
                        {
                            this.LogWarning("Song with id '{songId}' has not been found. Skipping.", id);
                            continue;
                        }

                        obj.songs.Add(id, song);
                    }
                }

                // load attempts
                {
                    int attemptCount = stream.ReadInt32();
                    obj.Attempts = new List <SongAttempt>(attemptCount);

                    for (int i = 0; i < attemptCount; i++)
                    {
                        var attempt = new SongAttempt();

                        Guid songId = new Guid();
                        guidSerializer.Serialize(ref songId, mode, stream);

                        if (!obj.songs.TryGetValue(songId, out Song song))
                        {
                            this.LogWarning("Song with id '{songId}' hasn't been loaded in the library. Removing entry from history.", songId);
                            song = null;
                        }

                        attempt.Song = song;

                        dateSerializer.Serialize(ref attempt.AttemptTime, mode, stream);
                        timeSerializer.Serialize(ref attempt.AttemptLength, mode, stream);
                        attempt.Score         = stream.ReadInt64();
                        attempt.ZombiesKilled = stream.ReadInt32();
                        attempt.Failed        = stream.ReadBoolean();

                        if (attempt.Song != null)
                        {
                            obj.Attempts.Add(attempt);
                        }
                    }
                }
            }
            else // serialize
            {
                var ids = obj.songs.Keys;
                // serialize the collection of songs - we just store their ids here, as each song has a URL
                {
                    stream.Write(ids.Count);
                    foreach (Guid id in ids)
                    {
                        guidSerializer.Serialize(id, stream);
                    }
                }

                // serialize attempts
                {
                    stream.Write(obj.Attempts.Count);
                    foreach (var attempt in obj.Attempts)
                    {
                        guidSerializer.Serialize(obj.songs.First(kvp => kvp.Value == attempt.Song).Key, stream);
                        dateSerializer.Serialize(attempt.AttemptTime, stream);
                        timeSerializer.Serialize(attempt.AttemptLength, stream);
                        stream.Write(attempt.Score);
                        stream.Write(attempt.ZombiesKilled);
                        stream.Write(attempt.Failed);
                    }
                }
            }
        }