Esempio n. 1
0
        private void SaveAssetsAndDeleteAChild(AssetManager assetManager)
        {
            var simpleAsset = new SimpleAsset("Pa", new SimpleAsset("Son", null));
            assetManager.Save(simpleAsset);
            var databaseFileProvider = (DatabaseFileProvider)VirtualFileSystem.ResolveProvider("/db", true).Provider;
            databaseFileProvider.AssetIndexMap.WaitPendingOperations();

            ObjectId childId;
            databaseFileProvider.AssetIndexMap.TryGetValue("SimpleAssets/Son", out childId);

            VirtualFileSystem.FileDelete(FileOdbBackend.BuildUrl(VirtualFileSystem.ApplicationDatabasePath, childId));
        }
Esempio n. 2
0
        public void TestSaveAndLoadEntities()
        {
            InitializeAssetDatabase();
            var assetManager = new AssetManager();

            var entity = new Entity();
            entity.Transform.Position = new Vector3(100.0f, 0.0f, 0.0f);
            assetManager.Save("EntityAssets/Entity", entity);

            GC.Collect();

            var entity2 = assetManager.Load<Entity>("EntityAssets/Entity");
            Assert.AreEqual(entity.Transform.Position, entity2.Transform.Position);
        }
Esempio n. 3
0
        protected override Task<ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();

            Image image;
            using (var fileStream = new FileStream(SourcePath, FileMode.Open, FileAccess.Read))
            {
                image = Image.Load(fileStream);
            }
            assetManager.Save(Location, image);
            image.Dispose();

            return Task.FromResult(ResultStatus.Successful);
        }
Esempio n. 4
0
        /// <summary>
        /// The method to override containing the actual command code. It is called by the <see cref="DoCommand" /> function
        /// </summary>
        /// <param name="commandContext">The command context.</param>
        /// <returns>Task{ResultStatus}.</returns>
        protected override async Task<ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();

            while (Interlocked.Increment(ref spawnedCommands) >= 2)
            {
                Interlocked.Decrement(ref spawnedCommands);
                await Task.Delay(1, CancellationToken);
            }

            try
            {
                object exportedObject;

                switch (Mode)
                {
                    case ExportMode.Animation:
                        exportedObject = ExportAnimation(commandContext, assetManager);
                        break;
                    case ExportMode.Skeleton:
                        exportedObject = ExportSkeleton(commandContext, assetManager);
                        break;
                    case ExportMode.Model:
                        exportedObject = ExportModel(commandContext, assetManager);
                        break;
                    default:
                        commandContext.Logger.Error("Unknown export type [{0}] {1}", Mode, ContextAsString);
                        return ResultStatus.Failed;
                }

                if (exportedObject != null)
                    assetManager.Save(Location, exportedObject);

                commandContext.Logger.Verbose("The {0} has been successfully imported.", ContextAsString);

                return ResultStatus.Successful;
            }
            catch (Exception ex)
            {
                commandContext.Logger.Error("Unexpected error while importing {0}", ex, ContextAsString);
                return ResultStatus.Failed;
            }
            finally
            {
                Interlocked.Decrement(ref spawnedCommands);
            }
        }
Esempio n. 5
0
        protected override Task<ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();

            // Load image
            var image = assetManager.Load<Image>(InputUrl);

            // Initialize TextureTool library
            using (var texTool = new TextureTool())
            using (var texImage = texTool.Load(image))
            {
                var outputFormat = Format.HasValue ? Format.Value : image.Description.Format;

                // Apply transformations
                texTool.Decompress(texImage);
                if (IsAbsolute)
                {
                    texTool.Resize(texImage, (int)Width, (int)Height, Filter.Rescaling.Lanczos3);
                }
                else
                {
                    texTool.Rescale(texImage, Width / 100.0f, Height / 100.0f, Filter.Rescaling.Lanczos3);
                }

                // Generate mipmaps
                if (GenerateMipmaps)
                {
                    texTool.GenerateMipMaps(texImage, Filter.MipMapGeneration.Box);
                }

                // Convert/Compress to output format
                texTool.Compress(texImage, outputFormat);

                // Save
                using (var outputImage = texTool.ConvertToParadoxImage(texImage))
                {
                    assetManager.Save(OutputUrl, outputImage);

                    commandContext.Logger.Verbose("Compression successful [{3}] to ({0}x{1},{2})",
                                                  outputImage.Description.Width,
                                                  outputImage.Description.Height, outputImage.Description.Format, OutputUrl);
                }
            }

            return Task.FromResult(ResultStatus.Successful);
        }
Esempio n. 6
0
        public static ResultStatus ImportTextureImage(TextureTool textureTool, TexImage texImage, ImportParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            var assetManager = new AssetManager();

            // Apply transformations
            textureTool.Decompress(texImage, parameters.IsSRgb);

            // Special case when the input texture is monochromatic but it is supposed to be a color and we are working in SRGB
            // In that case, we need to transform it to a supported SRGB format (R8G8B8A8_UNorm_SRgb)
            // TODO: As part of a conversion phase, this code may be moved to a dedicated method in this class at some point
            if (parameters.TextureHint == TextureHint.Color && parameters.IsSRgb && (texImage.Format == PixelFormat.R8_UNorm || texImage.Format == PixelFormat.A8_UNorm))
            {
                textureTool.Convert(texImage, PixelFormat.R8G8B8A8_UNorm_SRgb);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            var fromSize =  new Size2(texImage.Width, texImage.Height);
            var targetSize = parameters.DesiredSize;

            // Resize the image
            if (parameters.IsSizeInPercentage)
            {
                targetSize = new Size2((int)(fromSize.Width * targetSize.Width / 100.0f), (int)(fromSize.Height * targetSize.Height / 100.0f));
            }

            // Find the target size
            targetSize = FindBestTextureSize(parameters, targetSize, logger);

            // Resize the image only if needed
            if (targetSize != fromSize)
            {
                textureTool.Resize(texImage, targetSize.Width, targetSize.Height, Filter.Rescaling.Lanczos3);
            }

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // texture size is now determined, we can cache it
            var textureSize = new Int2(texImage.Width, texImage.Height);

            // determine the alpha format of the texture when set to Auto
            // Note: this has to be done before the ColorKey transformation in order to be able to take advantage of image file AlphaDepth information
            if(parameters.DesiredAlpha == AlphaFormat.Auto)
            {
                var colorKey = parameters.ColorKeyEnabled? (Color?)parameters.ColorKeyColor : null;
                var alphaLevel = textureTool.GetAlphaLevels(texImage, new Rectangle(0, 0, textureSize.X, textureSize.Y), colorKey, logger);
                parameters.DesiredAlpha = alphaLevel.ToAlphaFormat();
            }

            // Apply the color key
            if (parameters.ColorKeyEnabled)
                textureTool.ColorKey(texImage, parameters.ColorKeyColor);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // Pre-multiply alpha only for relevant formats 
            if (parameters.PremultiplyAlpha && texImage.Format.HasAlpha32Bits())
                textureTool.PreMultiplyAlpha(texImage);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;


            // Generate mipmaps
            if (parameters.GenerateMipmaps)
            {
                var boxFilteringIsSupported = !texImage.Format.IsSRgb() || (MathUtil.IsPow2(textureSize.X) && MathUtil.IsPow2(textureSize.Y));
                textureTool.GenerateMipMaps(texImage, boxFilteringIsSupported? Filter.MipMapGeneration.Box: Filter.MipMapGeneration.Linear);
            }
                
            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;


            // Convert/Compress to output format
            // TODO: Change alphaFormat depending on actual image content (auto-detection)?
            var outputFormat = DetermineOutputFormat(parameters, textureSize, texImage.Format);
            textureTool.Compress(texImage, outputFormat, (TextureConverter.Requests.TextureQuality)parameters.TextureQuality);

            if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                return ResultStatus.Cancelled;

            // Save the texture
            using (var outputImage = textureTool.ConvertToParadoxImage(texImage))
            {
                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                assetManager.Save(parameters.OutputUrl, outputImage.ToSerializableVersion());

                logger.Info("Compression successful [{3}] to ({0}x{1},{2})", outputImage.Description.Width, outputImage.Description.Height, outputImage.Description.Format, parameters.OutputUrl);
            }

            return ResultStatus.Successful;
        }
Esempio n. 7
0
        public static ResultStatus ImportAndSaveTextureImage(UFile sourcePath, string outputUrl, TextureAsset textureAsset, TextureConvertParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            var assetManager = new AssetManager();

            using (var texTool = new TextureTool())
            using (var texImage = texTool.Load(sourcePath, textureAsset.SRgb))
            {
                // Apply transformations
                texTool.Decompress(texImage, textureAsset.SRgb);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                var fromSize =  new Size2(texImage.Width, texImage.Height);
                var targetSize = new Size2((int)textureAsset.Width, (int)textureAsset.Height);

                // Resize the image
                if (textureAsset.IsSizeInPercentage)
                {
                    targetSize = new Size2((int)(fromSize.Width * (float)textureAsset.Width / 100.0f), (int)(fromSize.Height * (float) textureAsset.Height / 100.0f));
                }

                // Find the target size
                targetSize = FindBestTextureSize(textureAsset.Format, parameters.GraphicsPlatform, parameters.GraphicsProfile, fromSize, targetSize, textureAsset.GenerateMipmaps, logger);

                // Resize the image only if needed
                if (targetSize != fromSize)
                {
                    texTool.Resize(texImage, targetSize.Width, targetSize.Height, Filter.Rescaling.Lanczos3);
                }

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                // texture size is now determined, we can cache it
                var textureSize = new Int2(texImage.Width, texImage.Height);

                // Apply the color key
                if (textureAsset.ColorKeyEnabled)
                    texTool.ColorKey(texImage, textureAsset.ColorKeyColor);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Pre-multiply alpha
                if (textureAsset.PremultiplyAlpha)
                    texTool.PreMultiplyAlpha(texImage);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Generate mipmaps
                if (textureAsset.GenerateMipmaps)
                {
                    var boxFilteringIsSupported = texImage.Format != PixelFormat.B8G8R8A8_UNorm_SRgb || (IsPowerOfTwo(textureSize.X) && IsPowerOfTwo(textureSize.Y));
                    texTool.GenerateMipMaps(texImage, boxFilteringIsSupported? Filter.MipMapGeneration.Box: Filter.MipMapGeneration.Linear);
                }
                
                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;


                // Convert/Compress to output format
                // TODO: Change alphaFormat depending on actual image content (auto-detection)?
                var outputFormat = DetermineOutputFormat(textureAsset, parameters, textureSize, texImage.Format, parameters.Platform, parameters.GraphicsPlatform, parameters.GraphicsProfile);
                texTool.Compress(texImage, outputFormat, (TextureConverter.Requests.TextureQuality)parameters.TextureQuality);

                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                    return ResultStatus.Cancelled;

                // Save the texture
                using (var outputImage = texTool.ConvertToParadoxImage(texImage))
                {
                    if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                        return ResultStatus.Cancelled;

                    assetManager.Save(outputUrl, outputImage.ToSerializableVersion());

                    logger.Info("Compression successful [{3}] to ({0}x{1},{2})", outputImage.Description.Width, outputImage.Description.Height, outputImage.Description.Format, outputUrl);
                }
            }

            return ResultStatus.Successful;
        }
Esempio n. 8
0
        protected override async Task<ResultStatus> DoCommandOverride(ICommandContext commandContext)
        {
            var assetManager = new AssetManager();
            DataContainer result = null;

            switch (Source.Type)
            {
                case UrlType.File:
                    using (var fileStream = new FileStream(Source.Path, FileMode.Open, FileAccess.Read))
                    {
                        if (!WaitDelay())
                            return ResultStatus.Cancelled;

                        result = DataContainer.Load(fileStream);
                    }
                    break;
                case UrlType.ContentLink:
                case UrlType.Content:
                    var container = assetManager.Load<DataContainer>(Source.Path);

                        if (!WaitDelay())
                            return ResultStatus.Cancelled;

                     result = container.Alterate();
                  break;
            }

            assetManager.Save(OutputUrl, result);

            var tasksToWait = CommandsToSpawn.Select(commandContext.ScheduleAndExecuteCommand);
            await Task.WhenAll(tasksToWait);

            foreach (ObjectUrl inputDep in InputDependencies)
            {
                commandContext.RegisterInputDependency(inputDep);
            }
            return ResultStatus.Successful;
        }
Esempio n. 9
0
        public void TestImportModelSimple()
        {
            var file = Path.Combine(Environment.CurrentDirectory, @"scenes\goblin.fbx");

            // Create a project with an asset reference a raw file
            var project = new Package { FullPath = Path.Combine(Environment.CurrentDirectory, "ModelAssets", "ModelAssets" + Package.PackageFileExtension) };
            using (var session = new PackageSession(project))
            {
                var importSession = new AssetImportSession(session);

                // ------------------------------------------------------------------
                // Step 1: Add files to session
                // ------------------------------------------------------------------
                importSession.AddFile(file, project, UDirectory.Empty);

                // ------------------------------------------------------------------
                // Step 2: Stage assets
                // ------------------------------------------------------------------
                var stageResult = importSession.Stage();
                Assert.IsTrue(stageResult);
                Assert.AreEqual(0, project.Assets.Count);

                // ------------------------------------------------------------------
                // Step 3: Import asset directly
                // ------------------------------------------------------------------
                importSession.Import();
                Assert.AreEqual(4, project.Assets.Count);
                var assetItem = project.Assets.FirstOrDefault(item => item.Asset is EntityAsset);
                Assert.NotNull(assetItem);

                EntityAnalysis.UpdateEntityReferences(((EntityAsset)assetItem.Asset).Hierarchy);

                var assetCollection = new AssetItemCollection();
                // Remove directory from the location
                assetCollection.Add(assetItem);

                Console.WriteLine(assetCollection.ToText());

                //session.Save();

                // Create and mount database file system
                var objDatabase = new ObjectDatabase("/data/db", "index", "/local/db");
                var databaseFileProvider = new DatabaseFileProvider(objDatabase);
                AssetManager.GetFileProvider = () => databaseFileProvider;

                ((EntityAsset)assetItem.Asset).Hierarchy.Entities[0].Components.RemoveWhere(x => x.Key != TransformComponent.Key);
                //((EntityAsset)assetItem.Asset).Data.Entities[1].Components.RemoveWhere(x => x.Key != SiliconStudio.Paradox.Engine.TransformComponent.Key);

                var assetManager = new AssetManager();
                assetManager.Save("Entity1", ((EntityAsset)assetItem.Asset).Hierarchy);

                assetManager = new AssetManager();
                var entity = assetManager.Load<Entity>("Entity1");

                var entity2 = entity.Clone();

                var entityAsset = (EntityAsset)assetItem.Asset;
                entityAsset.Hierarchy.Entities[0].Components.Add(TransformComponent.Key, new TransformComponent());

                var entityAsset2 = (EntityAsset)AssetCloner.Clone(entityAsset);
                entityAsset2.Hierarchy.Entities[0].Components.Get(TransformComponent.Key).Position = new Vector3(10.0f, 0.0f, 0.0f);

                AssetMerge.Merge(entityAsset, entityAsset2, null, AssetMergePolicies.MergePolicyAsset2AsNewBaseOfAsset1);
            }
        }
Esempio n. 10
0
 private static void SaveCyclicallyReferencedAssets(AssetManager assetManager)
 {
     var simpleAsset = new SimpleAsset("First", new SimpleAsset("Second", new SimpleAsset("Third", null)));
     simpleAsset.Child.Child.Child = simpleAsset;
     assetManager.Save(simpleAsset);
 }
Esempio n. 11
0
 private void SaveChangeResaveAssets(AssetManager assetManager)
 {
     var simpleAsset = new SimpleAsset("Grandpa", new SimpleAsset("Pa", new SimpleAsset("Son", null)));
     assetManager.Save(simpleAsset);
     simpleAsset.Dble = 22.0;
     simpleAsset.Child.Dble = 42.0;
     assetManager.SaveSingle(simpleAsset);
 }
Esempio n. 12
0
 private static void SaveSimpleAssets(AssetManager assetManager)
 {
     var simpleAsset = new SimpleAsset("Grandpa", new SimpleAsset("Pa", new SimpleAsset("Son", null)));
     assetManager.Save(simpleAsset);
 }
Esempio n. 13
0
        private void SaveComplexAssets(AssetManager assetManager)
        {
            var ass1 = new ComplexAsset("First");
            var ass2 = new ComplexAsset("Second");
            var ass3 = new ComplexAsset("Third");

            ass1.Children.Add(ass2);
            ass1.FirstChild = ass2;
            ass1.Data = new MemberData { Asset = ass2, Num = 1 };

            ass2.Children.Add(ass3);
            ass2.FirstChild = ass3;

            ass3.Children.Add(ass1);
            ass3.Children.Add(ass2);
            ass3.FirstChild = ass2;
            ass3.Data = new MemberData { Asset = ass1, Num = 2 };

            assetManager.Save(ass1);
        }
Esempio n. 14
0
        public static void CreateAndSaveSeparateTextures(TextureTool texTool, TexImage texImage, string originalTextureURL, bool shouldGenerateMipMaps, PixelFormat outputFormat = PixelFormat.ETC1)
        {
            var assetManager = new AssetManager();
            var alphaTextureURL = GenerateAlphaTextureURL(originalTextureURL);
            var colorTextureURL = GenerateColorTextureURL(originalTextureURL);

            // create a new image containing only the alpha component
            texTool.Decompress(texImage, texImage.Format.IsSRgb());
            using (var alphaImage = texTool.CreateImageFromAlphaComponent(texImage))
            {
                // generate the mip-maps for the alpha component if required
                if (shouldGenerateMipMaps)
                    texTool.GenerateMipMaps(alphaImage, Filter.MipMapGeneration.Box);

                // save the alpha component
                texTool.Compress(alphaImage, outputFormat);
                using (var outputImage = texTool.ConvertToXenkoImage(alphaImage))
                    assetManager.Save(alphaTextureURL, outputImage.ToSerializableVersion());
            }

            // save the color component
            texTool.Decompress(texImage, texImage.Format.IsSRgb());
            texTool.Compress(texImage, outputFormat);
            using (var outputImage = texTool.ConvertToXenkoImage(texImage))
                assetManager.Save(colorTextureURL, outputImage.ToSerializableVersion());
        }