示例#1
0
        public static unsafe Image LoadFromMemory(IntPtr pSource, int size, bool makeACopy, GCHandle? handle)
        {
            var stream = new BinarySerializationReader(new NativeMemoryStream((byte*)pSource, size));

            // Read and check magic code
            var magicCode = stream.ReadUInt32();
            if (magicCode != MagicCode)
                return null;

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

            if (makeACopy)
            {
                var buffer = Utilities.AllocateMemory(size);
                Utilities.CopyMemory(buffer, pSource, size);
                pSource = buffer;
                makeACopy = false;
            }

            var image = new Image(imageDescription, pSource, 0, handle, !makeACopy);

            var totalSizeInBytes = stream.ReadInt32();
            if (totalSizeInBytes != image.TotalSizeInBytes)
                throw new InvalidOperationException("Image size is different than expected.");

            // Read image data
            stream.Serialize(image.DataPointer, image.TotalSizeInBytes);

            return image;
        }
示例#2
0
        private Shader(GraphicsDevice device, ShaderStage shaderStage, byte[] shaderStageBytecode)
            : base(device)
        {
            this.stage = shaderStage;

            var shaderStageGl = ConvertShaderStage(shaderStage);

            // Decode shader StageBytecode
            var binarySerializationReader = new BinarySerializationReader(new MemoryStream(shaderStageBytecode));
            var shaderBytecodeData = new OpenGLShaderBytecodeData();
            shaderBytecodeData.Serialize(binarySerializationReader, ArchiveMode.Deserialize);

            using (GraphicsDevice.UseOpenGLCreationContext())
            {
                resourceId = GL.CreateShader(shaderStageGl);

                if (shaderBytecodeData.IsBinary)
                {
                    GL.ShaderBinary(1, ref resourceId, (BinaryFormat)shaderBytecodeData.BinaryFormat, shaderBytecodeData.Binary, shaderBytecodeData.Binary.Length);
                }
                else
                {
                    GL.ShaderSource(resourceId, shaderBytecodeData.Source);
                    GL.CompileShader(resourceId);

                    var log = GL.GetShaderInfoLog(resourceId);

                    int compileStatus;
                    GL.GetShader(resourceId, ShaderParameter.CompileStatus, out compileStatus);

                    if (compileStatus != 1)
                        throw new InvalidOperationException(string.Format("Error while compiling GLSL shader: {0}", log));
                }
            }
        }
示例#3
0
 private static object DecodeObject(byte[] serializedObject)
 {
     var reader = new BinarySerializationReader(new MemoryStream(serializedObject));
     reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
     reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion);
     object command = null;
     reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null);
     return command;
 }
示例#4
0
        public static T Clone <T>(T obj)
        {
            var memoryStream = new MemoryStream();
            var writer       = new BinarySerializationWriter(memoryStream);

            writer.SerializeExtended(obj, ArchiveMode.Serialize);
            writer.Flush();

            var result = default(T);

            memoryStream.Seek(0, SeekOrigin.Begin);
            var reader = new BinarySerializationReader(memoryStream);

            reader.SerializeExtended(ref result, ArchiveMode.Deserialize);
            return(result);
        }
示例#5
0
        /// <summary>
        /// Clones the current value of this cloner with the specified new shadow registry (optional)
        /// </summary>
        /// <returns>A clone of the value associated with this cloner.</returns>
        private object Clone()
        {
            var stream = streamOrValueType as Stream;
            if (stream != null)
            {
                stream.Position = 0;
                var reader = new BinarySerializationReader(stream);
                reader.Context.SerializerSelector = ClonerSelector;
                var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0
                    ? ContentSerializerContext.AttachedReferenceSerialization.AsNull
                    : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion;
                reader.Context.Set(InvariantObjectListProperty, invariantObjects);
                reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag);
                object newObject = null;
                reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);

                // If there are any references, we would like to copy all dynamic properties from ShadowObject to the new instances
                if (objectReferences != null)
                {
                    var newObjectReferences = reader.Context.Get(MemberSerializer.ObjectDeserializeReferences);
                    foreach (var objRef in objectReferences)
                    {
                        var innerObject = objRef.Key;
                        var newInnerObject = newObjectReferences[objRef.Value];
                        // Copy only when objects are non-null
                        if (innerObject != null && newInnerObject != null)
                        {
                            ShadowObject.CopyDynamicProperties(innerObject, newInnerObject);
                            if ((flags & AssetClonerFlags.RemoveOverrides) != 0)
                            {
                                Override.RemoveFrom(newInnerObject);
                            }
                        }
                    }
                }

                return newObject;
            }
            // Else this is a value type, so it is cloned automatically
            return streamOrValueType;
        }
示例#6
0
        public static async Task UnpackAPK()
        {
            // get the apk last update time
            var packageManager = PlatformAndroid.Context.PackageManager;
            var packageInfo = packageManager.GetPackageInfo(PlatformAndroid.Context.PackageName, PackageInfoFlags.Activities);
            var lastUpdateTime = packageInfo.LastUpdateTime;
            var sourceDir = PlatformAndroid.Context.ApplicationInfo.SourceDir;

            // evaluate if asset data should be extracted from apk file
            var shouldExtractAssets = true;
            if (ApplicationTemporary.FileExists(LastExtractedApkFileName))
            {
                Int64 extractedLastUpdateTime = 0;
                using (var file = ApplicationTemporary.OpenStream(LastExtractedApkFileName, VirtualFileMode.Open, VirtualFileAccess.Read))
                {
                    var binaryReader = new BinarySerializationReader(file);
                    binaryReader.Serialize(ref extractedLastUpdateTime, ArchiveMode.Deserialize);
                }

                shouldExtractAssets = extractedLastUpdateTime != lastUpdateTime;
            }

            // Copy assets
            if (shouldExtractAssets)
            {
                var assets = PlatformAndroid.Context.Assets;

                // Make sure assets exists
                var logger = GlobalLogger.GetLogger("VFS");
                CopyFileOrDirectory(logger, sourceDir, "assets/data/", string.Empty);

                // update value of extracted last update time
                using (var stream = ApplicationTemporary.OpenStream(LastExtractedApkFileName, VirtualFileMode.Create, VirtualFileAccess.Write, VirtualFileShare.None))
                {
                    var binaryWriter = new BinarySerializationWriter(stream);
                    binaryWriter.Write(lastUpdateTime);
                }
            }
        }
示例#7
0
 /// <summary>
 /// Clones the current value of this cloner with the specified new shadow registry (optional)
 /// </summary>
 /// <returns>A clone of the value associated with this cloner.</returns>
 private object Clone()
 {
     var stream = streamOrValueType as Stream;
     if (stream != null)
     {
         stream.Position = 0;
         var reader = new BinarySerializationReader(stream);
         reader.Context.SerializerSelector = ClonerSelector;
         var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0
             ? ContentSerializerContext.AttachedReferenceSerialization.AsNull
             : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion;
         reader.Context.Set(InvariantObjectListProperty, invariantObjects);
         reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag);
         reader.Context.Set(MemberSerializer.ObjectDeserializeCallback, OnObjectDeserialized);
         object newObject = null;
         reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);
         return newObject;
     }
     // Else this is a value type, so it is cloned automatically
     return streamOrValueType;
 }
示例#8
0
        private static void Collect(HashSet<ObjectId> objectIds, ObjectId objectId, IAssetIndexMap assetIndexMap)
        {
            // Already added?
            if (!objectIds.Add(objectId))
                return;

            using (var stream = AssetManager.FileProvider.OpenStream("obj/" + objectId, VirtualFileMode.Open, VirtualFileAccess.Read))
            {
                // Read chunk header
                var streamReader = new BinarySerializationReader(stream);
                var header = ChunkHeader.Read(streamReader);

                // Only process chunks
                if (header != null)
                {
                    if (header.OffsetToReferences != -1)
                    {
                        // Seek to where references are stored and deserialize them
                        streamReader.NativeStream.Seek(header.OffsetToReferences, SeekOrigin.Begin);

                        List<ChunkReference> references = null;
                        streamReader.Serialize(ref references, ArchiveMode.Deserialize);

                        foreach (var reference in references)
                        {
                            ObjectId refObjectId;
                            var databaseFileProvider = DatabaseFileProvider.ResolveObjectId(reference.Location, out refObjectId);
                            if (databaseFileProvider != null)
                            {
                                Collect(objectIds, refObjectId, databaseFileProvider.AssetIndexMap);
                            }
                        }
                    }
                }
            }
        }
示例#9
0
        public void TestShaderParametersSerialization()
        {
            // Test serialization
            var shaderParameters = new ShaderMixinParameters("Test");
            shaderParameters.Set(PropertyInt, 5);
            var subShaderParameters = new ShaderMixinParameters("Sub");
            subShaderParameters.Set(PropertyInt, 6);
            shaderParameters.Set(PropertySub, subShaderParameters);

            var subShaderParametersArray = new ShaderMixinParameters[1];
            var subShaderParametersArray1 = new ShaderMixinParameters("InArray1");
            subShaderParametersArray[0] = subShaderParametersArray1;
            subShaderParametersArray1.Set(PropertyInt, 7);
            shaderParameters.Set(PropertySubs, subShaderParametersArray);

            var memoryStream = new MemoryStream();
            var writer = new BinarySerializationWriter(memoryStream);
            writer.Write(shaderParameters);
            writer.Flush();
            memoryStream.Position = 0;

            var reader = new BinarySerializationReader(memoryStream);
            var shaderParametersReloaded = reader.Read<ShaderMixinParameters>();

            // They should be strictly equal
            Assert.That(shaderParametersReloaded.IsSubsetOf(shaderParameters), Is.True);
            Assert.That(shaderParameters.IsSubsetOf(shaderParametersReloaded), Is.True);

            // Test subset
            // Check that by removing one key from the original parameters, the reloaded version is
            // no longer a subset
            subShaderParametersArray1.Remove(PropertyInt);
            Assert.That(shaderParametersReloaded.IsSubsetOf(shaderParameters), Is.False);
        }
示例#10
0
 /// <summary>
 /// Loads an <see cref="EffectBytecode" /> from a stream.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <returns>EffectBytecode or null if the magic header is not matching</returns>
 /// <exception cref="System.ArgumentNullException">stream</exception>
 public static EffectBytecode FromStream(Stream stream)
 {
     if (stream == null) throw new ArgumentNullException("stream");
     var reader = new BinarySerializationReader(stream);
     var version = reader.Read<uint>();
     // Version is not matching, return null
     if (version != MagicHeader)
     {
         return null;
     }
     return reader.Read<EffectBytecode>();
 }
示例#11
0
        public void Test()
        {
            var prefab = new PrefabAsset();

            var modelComponent = new ModelComponent();
            var entity = new Entity()
            {
                modelComponent
            };
            prefab.Hierarchy.Entities.Add(entity);
            prefab.Hierarchy.RootEntities.Add(entity.Id);

            var material1 = new MaterialNull();
            IdentifiableHelper.SetId(material1, new Guid("39E2B226-8752-4678-8E93-76FFBFBA337B"));
            var material2 = new MaterialNull();
            IdentifiableHelper.SetId(material2, new Guid("CC4F1B31-FBB7-4360-A3E7-060BDFDA0695"));
            modelComponent.Materials.Add(material1);
            modelComponent.Materials.Add(material2);

            Action<PrefabAsset> checkPrefab = (newPrefab) =>
            {
                var previousEntityDesign = newPrefab.Hierarchy.Entities.FirstOrDefault();

                Assert.NotNull(previousEntityDesign);

                var previousEntity = previousEntityDesign.Entity;


                var component = previousEntity.Get<ModelComponent>();
                Assert.NotNull(component);

                Assert.AreEqual(2, component.Materials.Count);

                var newMaterial1 = component.Materials[0];
                Assert.AreEqual(IdentifiableHelper.GetId(material1), IdentifiableHelper.GetId(newMaterial1));
                var newMaterial2 = component.Materials[1];
                Assert.AreEqual(IdentifiableHelper.GetId(material2), IdentifiableHelper.GetId(newMaterial2));
            };

            // Test yaml serialization
            {
                using (var stream = new MemoryStream())
                {
                    AssetSerializer.Save(stream, prefab);

                    stream.Position = 0;
                    var serializedVersion = Encoding.UTF8.GetString(stream.ToArray());
                    Console.WriteLine(serializedVersion);

                    stream.Position = 0;
                    var newPrefab = (PrefabAsset)AssetSerializer.Load(stream, "myentity");
                    checkPrefab(newPrefab);
                }
            }

            // Test cloning
            var newPrefabClone = (PrefabAsset)AssetCloner.Clone(prefab);
            checkPrefab(newPrefabClone);

            // Test runtime serialization (runtime serialization is removing MaterialNull and replacing it by a null)
            {
                var stream = new MemoryStream();
                var writer = new BinarySerializationWriter(stream) { Context = { SerializerSelector = SerializerSelector.AssetWithReuse } };
                writer.SerializeExtended(entity, ArchiveMode.Serialize);
                writer.Flush();
                stream.Position = 0;

                var reader = new BinarySerializationReader(stream) { Context = { SerializerSelector = SerializerSelector.AssetWithReuse } };

                Entity newEntity = null;
                reader.SerializeExtended(ref newEntity, ArchiveMode.Deserialize);

                Assert.NotNull(newEntity);

                var component = newEntity.Get<ModelComponent>();
                Assert.NotNull(component);

                Assert.AreEqual(2, component.Materials.Count);

                Assert.Null(component.Materials[0]);
                Assert.Null(component.Materials[1]);
            }
        }
示例#12
0
        /// <summary>
        /// Reads an object instance from the specified byte buffer.
        /// </summary>
        /// <typeparam name="T">Type of the object to read</typeparam>
        /// <param name="buffer">The byte buffer to read the object instance.</param>
        /// <returns>An object instance of type T.</returns>
        public static T Read <T>([NotNull] byte[] buffer)
        {
            var reader = new BinarySerializationReader(new MemoryStream(buffer));

            return(reader.Read <T>());
        }
示例#13
0
        /// <summary>
        /// Reads an object instance from the specified stream.
        /// </summary>
        /// <typeparam name="T">Type of the object to read</typeparam>
        /// <param name="stream">The stream to read the object instance.</param>
        /// <returns>An object instance of type T.</returns>
        public static T Read <T>([NotNull] Stream stream)
        {
            var reader = new BinarySerializationReader(stream);

            return(reader.Read <T>());
        }
示例#14
0
        internal void LoadSoundInMemory()
        {
            if (PreloadedBuffer.Ptr != IntPtr.Zero) return;

            using (var soundStream = ContentManager.FileProvider.OpenStream(CompressedDataUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable))
            using (var decoder = new Celt(SampleRate, CompressedSoundSource.SamplesPerFrame, Channels, true))
            {
                var reader = new BinarySerializationReader(soundStream);
                var samplesPerPacket = CompressedSoundSource.SamplesPerFrame * Channels;

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

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

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

                AudioLayer.BufferFill(PreloadedBuffer, memory.Pointer, memory.Length * sizeof(short), SampleRate, Channels == 1);
                memory.Dispose();
            }
        }
        private KeyValuePair<EffectBytecode, EffectBytecodeCacheLoadSource> LoadEffectBytecode(DatabaseFileProvider database, ObjectId bytecodeId)
        {
            KeyValuePair<EffectBytecode, EffectBytecodeCacheLoadSource> bytecodePair;

            if (!bytecodes.TryGetValue(bytecodeId, out bytecodePair))
            {
                if (!bytecodesByPassingStorage.Contains(bytecodeId) && database.ObjectDatabase.Exists(bytecodeId))
                {
                    using (var stream = database.ObjectDatabase.OpenStream(bytecodeId))
                    {
                        var bytecode = EffectBytecode.FromStream(stream);

                        // Try to read an integer that would specify what kind of cache it belongs to (if undefined because of old versions, mark it as dynamic cache)
                        var cacheSource = EffectBytecodeCacheLoadSource.DynamicCache;
                        if (stream.Position < stream.Length)
                        {
                            var binaryReader = new BinarySerializationReader(stream);
                            cacheSource = (EffectBytecodeCacheLoadSource)binaryReader.ReadInt32();
                        }
                        bytecodePair = new KeyValuePair<EffectBytecode, EffectBytecodeCacheLoadSource>(bytecode, cacheSource);
                    }
                }
                if (bytecodePair.Key != null)
                {
                    bytecodes.Add(bytecodeId, bytecodePair);
                }
            }

            // Always check that the bytecode is in sync with hash sources on all platforms
            if (bytecodePair.Key != null && IsBytecodeObsolete(bytecodePair.Key))
            {
                bytecodes.Remove(bytecodeId);
                bytecodePair = new KeyValuePair<EffectBytecode, EffectBytecodeCacheLoadSource>(null, EffectBytecodeCacheLoadSource.JustCompiled);
            }

            return bytecodePair;
        }