public async Task <ActionResult> ListImportQueue(ImportParameters parameters)
        {
            var filter = new ImportQueueFilter()
            {
                FilterMessage = parameters.FilterMessage,
                ImportStatus  = (enums.ImportStatus)parameters.ImportStatusId.GetValueOrDefault(),
                Action        = ImportAction.ImportQueue
            };

            filter.InitialiseFromJson(parameters);

            var results = await ImportViewModel.GetModel(DataContext, filter);

            var jQueryResult = new JQueryDataTableResultModel(results.TotalRecords, results.TotalDisplayRecords);

            // Iterate through the results and put them in a format that can be used by jQuery datatables
            if (results.ImportQueue.CurrentPage.Any())
            {
                foreach (var result in results.ImportQueue.CurrentPage)
                {
                    jQueryResult.aaData.Add(result.ToJQueryDataTableResult());
                }
            }
            return(Json(jQueryResult));
        }
Exemplo n.º 2
0
        public async Task <List <ImportParameters> > UploadFilesToStorageAccountAndGnerateParameters()
        {
            List <ImportParameters>       returnValue  = new List <ImportParameters>();
            MultipartMemoryStreamProvider inputStreams = await requestInput.Content.ReadAsMultipartAsync();

            Dictionary <string, byte[]> fileData = inputStreams.ExtractStreams();
            var nvc = requestInput.RequestUri.ParseQueryString();

            string halbJahrParam = nvc["Halbjahr"]?.ToString();

            halbJahrParam = System.Web.HttpUtility.UrlDecode(halbJahrParam);

            string constring = Environment.GetEnvironmentVariable(ConnectionString);

            BlobServiceClient   blobServiceClient = new BlobServiceClient(constring);
            BlobContainerClient containerClient   = blobServiceClient.GetBlobContainerClient("imports");

            string instanceId = string.Empty;

            foreach (KeyValuePair <string, byte[]> kvp in fileData)
            {
                ImportParameters parameter = new ImportParameters();
                parameter.FileName        = string.Concat(kvp.Key, "_", Guid.NewGuid().ToString("N"));
                parameter.HalfYearSetting = halbJahrParam;
                BlobClient blob = containerClient.GetBlobClient(parameter.FileName);
                blob.Upload(new MemoryStream(kvp.Value));
                returnValue.Add(parameter);
            }
            return(returnValue);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="textureSize">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindMaximumTextureSize(ImportParameters parameters, Size2 textureSize, ILogger logger = null)
        {
            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (parameters.GraphicsProfile)
            {
            case GraphicsProfile.Level_11_0:
            case GraphicsProfile.Level_11_1:
            case GraphicsProfile.Level_11_2:
                maxTextureSize = 16384;
                break;

            default:
                throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger?.Error($"Graphic profile {parameters.GraphicsProfile} do not support texture with resolution {textureSize.Width} x {textureSize.Height} because it is larger than {maxTextureSize}. Please reduce texture size or upgrade your graphic profile.");
                return(new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize)));
            }

            return(textureSize);
        }
        public async Task <ActionResult> ImportPage(ImportParameters parameters)
        {
            Parameters = parameters;
            var importView = await GetModelFromParameters();

            return(View(importView));
        }
 public static ImportQueueFilter FromParameters(ImportParameters Parameters)
 {
     return(new ImportQueueFilter()
     {
         ImportQueueId = Parameters.ImportQueueId
     });
 }
        protected void ApplyColumns(ImportParameters importParameters, ColumnScores columnScores)
        {
            importParameters.Columns             = columnScores.Columns;
            importParameters.HeaderColumnsValues = columnScores.HeaderColumnValues;
            ImportEntity entity = importParameters.Entities.First();

            entity.ColumnValues = columnScores.EntityColumns;
        }
        public ActionResult ModalAction(ImportParameters parameters)
        {
            Parameters = parameters;
            ValidateImportParameters(Enum.GetName(Parameters.Action.GetType(), Parameters.Action));

            return(RedirectToAction(Enum.GetName(Parameters.Action.GetType(), Parameters.Action),
                                    ImportParameters.GetActionSpecificParameters(Parameters)));
        }
Exemplo n.º 8
0
        private void UpdateContact(Entity contact, Dictionary <string, string> contactValues)
        {
            UserConnection   userConnection        = Get <UserConnection>("UserConnection");
            var              importParamsGenerator = new BaseImportParamsGenerator();
            ImportParameters parameters            = importParamsGenerator.GenerateParameters(contact.Schema, contactValues);
            var              fileImporter          = new FileImporter(userConnection);

            fileImporter.ImportWithParams(parameters);
        }
Exemplo n.º 9
0
 static int Import(
     ImportParameters p)
 {
     _parameters = p;
     if (GetKeyManager(p) is IKeyManagement keyManagement)
     {
         keyManagement.ImportSymmetricKey(p.BinaryKey);
     }
     return(0);
 }
        public async Task <ActionResult> DeleteImport(ImportParameters parameters)
        {
            var filter     = new ImportQueueFilter(parameters.ImportQueueId.GetValueOrDefault());
            var importView = await GetModelFromParameters(parameters);

            filter.ImportStatus      = enums.ImportStatus.Cancelled;
            importView.CurrentImport = await DataContext.Import.UpdateStatus(filter);

            return(Json(JsonActionResult.GetSuccess(), JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 11
0
 /// <summary>
 /// Sets import session information.
 /// </summary>
 /// <param name="parameters">Import parameters.</param>
 public void SetImportSessionInfo(ImportParameters parameters)
 {
     FileName             = parameters.FileName;
     ImportObject         = parameters.ImportObject;
     TotalRowsCount       = parameters.TotalRowsCount;
     ProcessedRowsCount   = parameters.ProcessedRowsCount;
     ImportedRowsCount    = parameters.ImportedRowsCount;
     NotImportedRowsCount = parameters.TotalRowsCount - parameters.ImportedRowsCount;
     ImportTags           = parameters.ImportTags;
 }
Exemplo n.º 12
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="textureSizeRequested">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(ImportParameters parameters, Size2 textureSizeRequested, ILogger logger = null)
        {
            var textureSize = textureSizeRequested;

            // compressed DDS files has to have a size multiple of 4.
            if (parameters.GraphicsPlatform == GraphicsPlatform.Direct3D11 && parameters.DesiredFormat == TextureFormat.Compressed &&
                ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0))
            {
                textureSize.Width  = unchecked ((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked ((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3));
            }

            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (parameters.GraphicsProfile)
            {
            case GraphicsProfile.Level_9_1:
            case GraphicsProfile.Level_9_2:
            case GraphicsProfile.Level_9_3:
                if (parameters.GenerateMipmaps && (!MathUtil.IsPow2(textureSize.Width) || !MathUtil.IsPow2(textureSize.Height)))
                {
                    // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD
                    textureSize.Width  = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024);
                    textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024);
                    logger?.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize);
                }
                maxTextureSize = parameters.GraphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048;
                break;

            case GraphicsProfile.Level_10_0:
            case GraphicsProfile.Level_10_1:
                maxTextureSize = 8192;
                break;

            case GraphicsProfile.Level_11_0:
            case GraphicsProfile.Level_11_1:
            case GraphicsProfile.Level_11_2:
                maxTextureSize = 16384;
                break;

            default:
                throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger?.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " +
                              "Please reduce texture size or upgrade your graphic profile.", parameters.GraphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height);
                return(new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize)));
            }

            return(textureSize);
        }
        protected virtual ImportParameters GetImportParams(EntitySchema entitySchema)
        {
            var importParameters = new ImportParameters();

            importParameters.Entities = new List <ImportEntity>();
            var entity = new ImportEntity();

            importParameters.Entities.Add(entity);
            importParameters.RootSchemaUId = entitySchema.UId;
            return(importParameters);
        }
Exemplo n.º 14
0
 public static ImportQueue FromParameters(ImportParameters parameters)
 {
     return(new ImportQueue()
     {
         ProgrammeId = parameters.ProgrammeId.GetValueOrDefault(),
         ModelYear = parameters.ModelYear,
         Gateway = parameters.Gateway,
         DocumentId = parameters.DocumentId,
         FilePath = parameters.UploadFilePath,
         OriginalFileName = parameters.UploadFile.FileName
     });
 }
        public async Task <ActionResult> ModalContent(ImportParameters parameters)
        {
            if (parameters.Action != ImportAction.Upload)
            {
                ImportParametersValidator
                .ValidateImportParameters(parameters, ImportParametersValidator.ImportQueueIdentifier, DataContext);
            }

            var importView = GetModelFromParameters(parameters).Result;

            return(PartialView(GetContentPartialViewName(parameters.Action), importView));
        }
        public async Task <ActionResult> ContextMenu(ImportParameters parameters)
        {
            ImportParametersValidator.ValidateImportParameters(parameters, ImportParametersValidator.ImportQueueIdentifier, DataContext);

            var importView = await ImportViewModel.GetModel(
                DataContext,
                new ImportQueueFilter(parameters.ImportQueueId.Value)
            {
                Action = ImportAction.ImportQueueItem
            });

            return(PartialView("_ContextMenu", importView));
        }
Exemplo n.º 17
0
        public void PresentData(object data)
        {
            if (DataType != null)
            {
                foreach (PropertyInfo pi in DataType.GetProperties())
                {
                    if (ImportParameters.Contains(pi.Name))
                    {
                        if (pi.GetGetMethod().GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Count() == 0)
                        {
                            string headerText;
                            string bindingName;

                            headerText  = pi.Name;
                            bindingName = pi.Name;

                            if (pi.GetCustomAttributes(typeof(DisplayNameAttribute), false).Count() > 0)
                            {
                                headerText += "\n\r[" + ((DisplayNameAttribute)pi.GetCustomAttributes(typeof(DisplayNameAttribute), false)[0]).DisplayName + "]";
                            }

                            Column newColumn = new Column();
                            newColumn.Title     = headerText;
                            newColumn.FieldName = bindingName;

                            ImportGrid.Columns.Add(newColumn);

                            if (!Presenter.PropertyToExcelColumnIIndexDic.ContainsKey(bindingName))
                            {
                                Presenter.PropertyToExcelColumnIIndexDic.Add(bindingName, -1);
                            }
                        }
                    }
                }

                LoadDataToGrid();
            }

            if (ShowOpenFile)
            {
                OpenFileComponent.FileExtensions = FileExtension;
                OpenFileComponent.FileSelected  += new EventHandler(OpenFileComponent_FileSelected);
            }
            else
            {
                OpenFileComponent.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="outputFormat">The output format</param>
        /// <param name="textureSize">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(ImportParameters parameters, PixelFormat outputFormat, Size2 textureSize, ILogger logger = null)
        {
            bool isBlockCompressed =
                (outputFormat >= PixelFormat.BC1_Typeless && outputFormat <= PixelFormat.BC5_SNorm) ||
                (outputFormat >= PixelFormat.BC6H_Typeless && outputFormat <= PixelFormat.BC7_UNorm_SRgb);

            // compressed DDS files has to have a size multiple of 4.
            if (parameters.ShouldCompress && isBlockCompressed &&
                ((textureSize.Width % 4) != 0 || (textureSize.Height % 4) != 0))
            {
                textureSize.Width  = unchecked ((int)(((uint)(textureSize.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked ((int)(((uint)(textureSize.Height + 3)) & ~(uint)3));
            }

            return(FindMaximumTextureSize(parameters, textureSize, logger));
        }
Exemplo n.º 19
0
        public static async Task <string> FetchFile([ActivityTrigger] ImportParameters parameter, ILogger log)
        {
            string              constring         = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
            BlobServiceClient   blobServiceClient = new BlobServiceClient(constring);
            BlobContainerClient containerClient   = blobServiceClient.GetBlobContainerClient("imports");
            BlobClient          blob = containerClient.GetBlobClient(parameter.FileName);

            MemoryStream s = new MemoryStream();

            blob.DownloadTo(s);
            parameter.Content = s.ToArray();
            // Add Logic for Importing and replacing the following line
            List <ImportResult> returnValue = new List <ImportResult>();

            // Return the results
            return(JsonConvert.SerializeObject(returnValue));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Handles the form data.
        /// </summary>
        /// <param name="formData">The form data.</param>
        public void HandleForm(FormData formData)
        {
            Success  = true;
            FormData = formData;
            Guid webFormId = WebFormHelper.GetWebFormId(formData);

            if (webFormId.Equals(Guid.Empty))
            {
                SetErrorStatus(GeneratedWebFormLczUtilities
                               .GetLczStringValue("UnknownWebFormIdentifierMessage",
                                                  "WebFormHandler", _userConnection));
                return;
            }
            if (!(ImportParamsGenerator is IImportParamsGenerator))
            {
                SetErrorStatus(GeneratedWebFormLczUtilities
                               .GetLczStringValue("ImportParamsGeneratorImplementationMessage",
                                                  "WebFormHandler", _userConnection));
                return;
            }
            InitHandlers(webFormId);
            Guid newEntityId = SetUpNewEntityId(formData);

            FormData = PreProcessData(formData);
            EntitySchema     schema     = WebFormHelper.GetWebFormEntitySchema(webFormId, _userConnection);
            ImportParameters parameters =
                ((IImportParamsGenerator)ImportParamsGenerator).GenerateParameters(schema);

            if (!ImportParamsGenerator.Success)
            {
                SetErrorStatus(ImportParamsGenerator.ErrorMessage);
                return;
            }
            FileImporter.ImportEntitySaveError += (sender, args) => {
                SetErrorStatus(args.Message ?? args.Exception.Message, args.Exception);
            };
            FileImporter.ColumnProcessError += (sender, args) => {
                SetErrorStatus(args.Message);
            };
            FileImporter.ImportWithParams(parameters);
            if (Success)
            {
                PostProcessData(formData, webFormId, newEntityId);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="textureSizeRequested">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindMaximumTextureSize(ImportParameters parameters, Size2 textureSize, ILogger logger = null)
        {
            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (parameters.GraphicsProfile)
            {
            case GraphicsProfile.Level_9_1:
            case GraphicsProfile.Level_9_2:
            case GraphicsProfile.Level_9_3:
                if (parameters.GenerateMipmaps && (!MathUtil.IsPow2(textureSize.Width) || !MathUtil.IsPow2(textureSize.Height)))
                {
                    // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD
                    textureSize.Width  = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024);
                    textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024);
                    logger?.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize);
                }
                maxTextureSize = parameters.GraphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048;
                break;

            case GraphicsProfile.Level_10_0:
            case GraphicsProfile.Level_10_1:
                maxTextureSize = 8192;
                break;

            case GraphicsProfile.Level_11_0:
            case GraphicsProfile.Level_11_1:
            case GraphicsProfile.Level_11_2:
                maxTextureSize = 16384;
                break;

            default:
                throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger?.Error($"Graphic profile {parameters.GraphicsProfile} do not support texture with resolution {textureSize.Width} x {textureSize.Height} because it is larger than {maxTextureSize}. Please reduce texture size or upgrade your graphic profile.");
                return(new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize)));
            }

            return(textureSize);
        }
        //[Ignore("Slow manual test harness")]
        public void ImportFromRawFiles()
        {
            var idGenerator = new IdGenerator(IdGeneratorSequenceSeed);
            var dobihFile   = new DobihFile();

            var parameters = new ImportParameters
            {
                DobihFile       = dobihFile,
                MapProvider     = new MapProvider(idGenerator, new OsFile()),
                IdGenerator     = idGenerator,
                CountryProvider = new CountryProvider(idGenerator),
                ListProvider    = new ListProvider(idGenerator, dobihFile, new ListInfoProvider()),
                SectionProvider = new SectionProvider(idGenerator, dobihFile),
            };

            var sut = new DomainRootFactory(parameters).Build();

            AssertDomain(sut);
            sut.Save();
        }
 private async Task <ImportViewModel> GetModelFromParameters(ImportParameters parameters)
 {
     if (parameters.Action == ImportAction.DeleteImport)
     {
         return(await ImportViewModel.GetModel(
                    DataContext,
                    new ImportQueueFilter(parameters.ImportQueueId.GetValueOrDefault()) { Action = parameters.Action },
                    parameters.Action));
     }
     if (parameters.Action == ImportAction.Upload)
     {
         return(await ImportViewModel.GetModel(
                    DataContext,
                    new ImportQueueFilter()
         {
             Action = parameters.Action
         },
                    parameters.Action));
     }
     return(GetModelFromParameters().Result);
 }
        public ActionResult Upload(HttpPostedFileBase fileToUpload,
                                   string carLine,
                                   string modelYear,
                                   string gateway,
                                   int?documentId)
        {
            Parameters = new ImportParameters
            {
                Action     = ImportAction.Upload,
                UploadFile = fileToUpload,
                CarLine    = carLine,
                ModelYear  = modelYear,
                Gateway    = gateway,
                DocumentId = documentId
            };
            ValidateImportParameters(ImportParametersValidator.Upload);

            SetProgrammeId();
            SetUploadFilePath();
            SaveImportFileToFileSystem();
            QueueItemForProcessing();
            ProcessQueuedItem();
            //ValidateProcessedItem();
            RefreshQueuedItem();

            var retVal = JsonGetSuccess();

            if (CurrentQueuedItem.HasErrors)
            {
                retVal = JsonGetFailure(string.Format("Import Completed with {0} {1} error(s)",
                                                      CurrentQueuedItem.ErrorCount,
                                                      ImportQueue.GetErrorTypeAbbreviation(CurrentQueuedItem.ErrorType)));
            }

            return(retVal);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Sets import session information.
 /// </summary>
 /// <param name="parameters">Import parameters.</param>
 /// <param name="schemaName">Schema name.</param>
 public void SetImportSessionInfo(ImportParameters parameters, string schemaName)
 {
     SetImportSessionInfo(parameters);
     RootSchemaName = schemaName;
 }
Exemplo n.º 26
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;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Determine the output format of the texture depending on the platform and asset properties.
        /// </summary>
        /// <param name="parameters">The conversion request parameters</param>
        /// <param name="imageSize">The texture output size</param>
        /// <param name="inputImageFormat">The pixel format of the input image</param>
        /// <returns>The pixel format to use as output</returns>
        public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Int2 imageSize, PixelFormat inputImageFormat)
        {
            var hint = parameters.TextureHint;
            var alphaMode = parameters.DesiredAlpha;

            // Default output format
            var outputFormat = PixelFormat.R8G8B8A8_UNorm;
            switch (parameters.DesiredFormat)
            {
                case TextureFormat.Compressed:
                    switch (parameters.Platform)
                    {
                        case PlatformType.Android:
                            if (inputImageFormat.IsHDR())
                            {
                                outputFormat = inputImageFormat;
                            }
                            else
                            {
                                switch (parameters.GraphicsProfile)
                                {
                                    case GraphicsProfile.Level_9_1:
                                    case GraphicsProfile.Level_9_2:
                                    case GraphicsProfile.Level_9_3:
                                        outputFormat = alphaMode == AlphaFormat.None && !parameters.IsSRgb ? PixelFormat.ETC1 : parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                                        break;
                                    case GraphicsProfile.Level_10_0:
                                    case GraphicsProfile.Level_10_1:
                                    case GraphicsProfile.Level_11_0:
                                    case GraphicsProfile.Level_11_1:
                                    case GraphicsProfile.Level_11_2:
                                        // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                                        outputFormat = alphaMode == AlphaFormat.None && !parameters.IsSRgb ? PixelFormat.ETC1 : parameters.IsSRgb ? PixelFormat.ETC2_RGBA_SRgb : PixelFormat.ETC2_RGBA;
                                        break;
                                    default:
                                        throw new ArgumentOutOfRangeException("GraphicsProfile");
                                }
                            }
                            break;
                        case PlatformType.iOS:
                            // PVRTC works only for square POT textures
                            if (inputImageFormat.IsHDR())
                            {
                                outputFormat = inputImageFormat;
                            }
                            else if (SupportPVRTC(imageSize))
                            {
                                switch (alphaMode)
                                {
                                    case AlphaFormat.None:
                                        outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGB_SRgb : PixelFormat.PVRTC_4bpp_RGB;
                                        break;
                                    case AlphaFormat.Mask:
                                        // DXT1 handles 1-bit alpha channel
                                        // TODO: Not sure about the equivalent here?
                                        outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGBA_SRgb : PixelFormat.PVRTC_4bpp_RGBA;
                                        break;
                                    case AlphaFormat.Explicit:
                                    case AlphaFormat.Interpolated:
                                        // DXT3 is good at sharp alpha transitions
                                        // TODO: Not sure about the equivalent here?
                                        outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGBA_SRgb : PixelFormat.PVRTC_4bpp_RGBA;
                                        break;
                                    default:
                                        throw new ArgumentOutOfRangeException();
                                }
                            }
                            else
                            {
                                outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                            }
                            break;
                        case PlatformType.Windows:
                        case PlatformType.WindowsPhone:
                        case PlatformType.WindowsStore:
                        case PlatformType.Windows10:
                            switch (parameters.GraphicsPlatform)
                            {
                                case GraphicsPlatform.Direct3D11:


                                    // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx
                                    // http://www.reedbeta.com/blog/2012/02/12/understanding-bcn-texture-compression-formats/
                                    // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                                    // Source data                                       Minimum required data compression resolution 	                  Recommended format	Minimum supported feature level
                                    // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                                    // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 0 or 1 bit(s) of alpha    BC1    Direct3D 9.1     (color maps, cutout color maps - 1 bit alpha, normal maps if memory is tight)
                                    // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 4 bits of alpha           BC2    Direct3D 9.1     (idem)
                                    // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits) with 8 bits of alpha            BC3    Direct3D 9.1     (color maps with alpha, packing color and mono maps together)
                                    // One-channel color                                 One color channel (8 bits)                                                  BC4    Direct3D 10      (Height maps, gloss maps, font atlases, any gray scales image)
                                    // Two-channel color	                             Two color channels (8 bits:8 bits)                                          BC5    Direct3D 10      (Tangent space normal maps)
                                    // Three-channel high dynamic range (HDR) color      Three color channels (16 bits:16 bits:16 bits) in "half" floating point*    BC6H   Direct3D 11      (HDR images)
                                    // Three-channel color, alpha channel optional       Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha    BC7    Direct3D 11      (High quality color maps, Color maps with full alpha)

                                    switch (alphaMode)
                                    {
                                        case AlphaFormat.None:
                                        case AlphaFormat.Mask:
                                            // DXT1 handles 1-bit alpha channel
                                            outputFormat = parameters.IsSRgb ? PixelFormat.BC1_UNorm_SRgb : PixelFormat.BC1_UNorm;
                                            break;
                                        case AlphaFormat.Explicit:
                                            // DXT3 is good at sharp alpha transitions
                                            outputFormat = parameters.IsSRgb ? PixelFormat.BC2_UNorm_SRgb : PixelFormat.BC2_UNorm;
                                            break;
                                        case AlphaFormat.Interpolated:
                                            // DXT5 is good at alpha gradients
                                            outputFormat = parameters.IsSRgb ? PixelFormat.BC3_UNorm_SRgb : PixelFormat.BC3_UNorm;
                                            break;
                                        default:
                                            throw new ArgumentOutOfRangeException();
                                    }

                                    // Overrides the format when profile is >= 10.0
                                    // Support some specific optimized formats based on the hint or input type
                                    if (parameters.GraphicsProfile >= GraphicsProfile.Level_10_0)
                                    {
                                        if (hint == TextureHint.NormalMap)
                                        {
                                            outputFormat = PixelFormat.BC5_SNorm;
                                        }
                                        else if (hint == TextureHint.Grayscale)
                                        {
                                            outputFormat = PixelFormat.BC4_UNorm;
                                        }
                                        else if (inputImageFormat.IsHDR())
                                        {
                                            // BC6H is too slow to compile
                                            //outputFormat = parameters.GraphicsProfile >= GraphicsProfile.Level_11_0 && alphaMode == AlphaFormat.None ? PixelFormat.BC6H_Uf16 : inputImageFormat;
                                            outputFormat = inputImageFormat;
                                        }
                                        // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now
                                    }
                                    break;
                                case GraphicsPlatform.OpenGLES: // OpenGLES on Windows
                                    if (inputImageFormat.IsHDR())
                                    {
                                        outputFormat = inputImageFormat;
                                    }
                                    else if (parameters.IsSRgb)
                                    {
                                        outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                                    }
                                    else
                                    {
                                        switch (parameters.GraphicsProfile)
                                        {
                                            case GraphicsProfile.Level_9_1:
                                            case GraphicsProfile.Level_9_2:
                                            case GraphicsProfile.Level_9_3:
                                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm;
                                                break;
                                            case GraphicsProfile.Level_10_0:
                                            case GraphicsProfile.Level_10_1:
                                            case GraphicsProfile.Level_11_0:
                                            case GraphicsProfile.Level_11_1:
                                            case GraphicsProfile.Level_11_2:
                                                // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA;
                                                break;
                                            default:
                                                throw new ArgumentOutOfRangeException("GraphicsProfile");
                                        }
                                    }
                                    break;
                                default:
                                    // OpenGL on Windows
                                    // TODO: Need to handle OpenGL Desktop compression
                                    outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                                    break;
                            }
                            break;
                        default:
                            throw new NotSupportedException("Platform " + parameters.Platform + " is not supported by TextureTool");
                    }
                    break;
                case TextureFormat.Color16Bits:
                    if (parameters.IsSRgb)
                    {
                        outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                    }
                    else
                    {
                        if (alphaMode == AlphaFormat.None)
                        {
                            outputFormat = PixelFormat.B5G6R5_UNorm;
                        }
                        else if (alphaMode == AlphaFormat.Mask)
                        {
                            outputFormat = PixelFormat.B5G5R5A1_UNorm;
                        }
                    }
                    break;
                case TextureFormat.Color32Bits:
                    if (parameters.IsSRgb)
                    {
                        outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                    }
                    break;
                case TextureFormat.AsIs:
                    outputFormat = inputImageFormat;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            return outputFormat;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="textureSizeRequested">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(ImportParameters parameters, Size2 textureSizeRequested, ILogger logger = null)
        {
            var textureSize = textureSizeRequested;

            // compressed DDS files has to have a size multiple of 4.
            if (parameters.GraphicsPlatform == GraphicsPlatform.Direct3D11 && parameters.DesiredFormat == TextureFormat.Compressed
                && ((textureSizeRequested.Width % 4) != 0 || (textureSizeRequested.Height % 4) != 0))
            {
                textureSize.Width = unchecked((int)(((uint)(textureSizeRequested.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked((int)(((uint)(textureSizeRequested.Height + 3)) & ~(uint)3));
            }

            var maxTextureSize = 0;

            // determine if the desired size if valid depending on the graphics profile
            switch (parameters.GraphicsProfile)
            {
                case GraphicsProfile.Level_9_1:
                case GraphicsProfile.Level_9_2:
                case GraphicsProfile.Level_9_3:
                    if (parameters.GenerateMipmaps && (!MathUtil.IsPow2(textureSize.Width) || !MathUtil.IsPow2(textureSize.Height)))
                    {
                        // TODO: TEMPORARY SETUP A MAX TEXTURE OF 1024. THIS SHOULD BE SPECIFIED DONE IN THE ASSET INSTEAD
                        textureSize.Width = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Width), 1024);
                        textureSize.Height = Math.Min(MathUtil.NextPowerOfTwo(textureSize.Height), 1024);
                        logger?.Warning("Graphic profiles 9.1/9.2/9.3 do not support mipmaps with textures that are not power of 2. Asset is automatically resized to " + textureSize);
                    }
                    maxTextureSize = parameters.GraphicsProfile >= GraphicsProfile.Level_9_3 ? 4096 : 2048;
                    break;
                case GraphicsProfile.Level_10_0:
                case GraphicsProfile.Level_10_1:
                    maxTextureSize = 8192;
                    break;
                case GraphicsProfile.Level_11_0:
                case GraphicsProfile.Level_11_1:
                case GraphicsProfile.Level_11_2:
                    maxTextureSize = 16384;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("graphicsProfile");
            }

            if (textureSize.Width > maxTextureSize || textureSize.Height > maxTextureSize)
            {
                logger?.Error("Graphic profile {0} do not support texture with resolution {2} x {3} because it is larger than {1}. " +
                             "Please reduce texture size or upgrade your graphic profile.", parameters.GraphicsProfile, maxTextureSize, textureSize.Width, textureSize.Height);
                return new Size2(Math.Min(textureSize.Width, maxTextureSize), Math.Min(textureSize.Height, maxTextureSize));
            }

            return textureSize;
        }
Exemplo n.º 29
0
        public static ResultStatus ImportTextureImage(TextureTool textureTool, TexImage texImage, ImportParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            var assetManager = new ContentManager();

            // 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.ConvertToXenkoImage(texImage))
            {
                if (cancellationToken.IsCancellationRequested) // abort the process if cancellation is demanded
                {
                    return(ResultStatus.Cancelled);
                }

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

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

            return(ResultStatus.Successful);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Determine the output format of the texture depending on the platform and asset properties.
        /// </summary>
        /// <param name="parameters">The conversion request parameters</param>
        /// <param name="imageSize">The texture output size</param>
        /// <param name="inputImageFormat">The pixel format of the input image</param>
        /// <returns>The pixel format to use as output</returns>
        public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Int2 imageSize, PixelFormat inputImageFormat)
        {
            var hint      = parameters.TextureHint;
            var alphaMode = parameters.DesiredAlpha;

            // Default output format
            var outputFormat = PixelFormat.R8G8B8A8_UNorm;

            switch (parameters.DesiredFormat)
            {
            case TextureFormat.Compressed:
                switch (parameters.Platform)
                {
                case PlatformType.Android:
                    if (inputImageFormat.IsHDR())
                    {
                        outputFormat = inputImageFormat;
                    }
                    else
                    {
                        switch (parameters.GraphicsProfile)
                        {
                        case GraphicsProfile.Level_9_1:
                        case GraphicsProfile.Level_9_2:
                        case GraphicsProfile.Level_9_3:
                            outputFormat = alphaMode == AlphaFormat.None && !parameters.IsSRgb ? PixelFormat.ETC1 : parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                            break;

                        case GraphicsProfile.Level_10_0:
                        case GraphicsProfile.Level_10_1:
                        case GraphicsProfile.Level_11_0:
                        case GraphicsProfile.Level_11_1:
                        case GraphicsProfile.Level_11_2:
                            // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                            outputFormat = alphaMode == AlphaFormat.None && !parameters.IsSRgb ? PixelFormat.ETC1 : parameters.IsSRgb ? PixelFormat.ETC2_RGBA_SRgb : PixelFormat.ETC2_RGBA;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException("GraphicsProfile");
                        }
                    }
                    break;

                case PlatformType.iOS:
                    // PVRTC works only for square POT textures
                    if (inputImageFormat.IsHDR())
                    {
                        outputFormat = inputImageFormat;
                    }
                    else if (SupportPVRTC(imageSize))
                    {
                        switch (alphaMode)
                        {
                        case AlphaFormat.None:
                            outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGB_SRgb : PixelFormat.PVRTC_4bpp_RGB;
                            break;

                        case AlphaFormat.Mask:
                            // DXT1 handles 1-bit alpha channel
                            // TODO: Not sure about the equivalent here?
                            outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGBA_SRgb : PixelFormat.PVRTC_4bpp_RGBA;
                            break;

                        case AlphaFormat.Explicit:
                        case AlphaFormat.Interpolated:
                            // DXT3 is good at sharp alpha transitions
                            // TODO: Not sure about the equivalent here?
                            outputFormat = parameters.IsSRgb ? PixelFormat.PVRTC_4bpp_RGBA_SRgb : PixelFormat.PVRTC_4bpp_RGBA;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }
                    }
                    else
                    {
                        outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                    }
                    break;

                case PlatformType.Windows:
                case PlatformType.WindowsPhone:
                case PlatformType.WindowsStore:
                case PlatformType.Windows10:
                case PlatformType.Linux:
                    switch (parameters.GraphicsPlatform)
                    {
                    case GraphicsPlatform.Direct3D11:
                    case GraphicsPlatform.Direct3D12:
                    case GraphicsPlatform.OpenGL:


                        // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx
                        // http://www.reedbeta.com/blog/2012/02/12/understanding-bcn-texture-compression-formats/
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Source data                                       Minimum required data compression resolution                     Recommended format	Minimum supported feature level
                        // ----------------------------------------------    ----------------------------------------------------                        ---    ---------------------------------
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 0 or 1 bit(s) of alpha    BC1    Direct3D 9.1     (color maps, cutout color maps - 1 bit alpha, normal maps if memory is tight)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits), with 4 bits of alpha           BC2    Direct3D 9.1     (idem)
                        // Three-channel color with alpha channel            Three color channels (5 bits:6 bits:5 bits) with 8 bits of alpha            BC3    Direct3D 9.1     (color maps with alpha, packing color and mono maps together)
                        // One-channel color                                 One color channel (8 bits)                                                  BC4    Direct3D 10      (Height maps, gloss maps, font atlases, any gray scales image)
                        // Two-channel color	                             Two color channels (8 bits:8 bits)                                          BC5    Direct3D 10      (Tangent space normal maps)
                        // Three-channel high dynamic range (HDR) color      Three color channels (16 bits:16 bits:16 bits) in "half" floating point*    BC6H   Direct3D 11      (HDR images)
                        // Three-channel color, alpha channel optional       Three color channels (4 to 7 bits per channel) with 0 to 8 bits of alpha    BC7    Direct3D 11      (High quality color maps, Color maps with full alpha)

                        switch (alphaMode)
                        {
                        case AlphaFormat.None:
                        case AlphaFormat.Mask:
                            // DXT1 handles 1-bit alpha channel
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC1_UNorm_SRgb : PixelFormat.BC1_UNorm;
                            break;

                        case AlphaFormat.Explicit:
                            // DXT3 is good at sharp alpha transitions
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC2_UNorm_SRgb : PixelFormat.BC2_UNorm;
                            break;

                        case AlphaFormat.Interpolated:
                            // DXT5 is good at alpha gradients
                            outputFormat = parameters.IsSRgb ? PixelFormat.BC3_UNorm_SRgb : PixelFormat.BC3_UNorm;
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        // Overrides the format when profile is >= 10.0
                        // Support some specific optimized formats based on the hint or input type
                        if (parameters.GraphicsProfile >= GraphicsProfile.Level_10_0)
                        {
                            if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.NormalMap)
                            {
                                outputFormat = PixelFormat.BC5_SNorm;
                            }
                            else if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.Grayscale)
                            {
                                outputFormat = PixelFormat.BC4_UNorm;
                            }
                            else if (inputImageFormat.IsHDR())
                            {
                                // BC6H is too slow to compile
                                //outputFormat = parameters.GraphicsProfile >= GraphicsProfile.Level_11_0 && alphaMode == AlphaFormat.None ? PixelFormat.BC6H_Uf16 : inputImageFormat;
                                outputFormat = inputImageFormat;
                            }
                            // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now
                        }
                        break;

                    case GraphicsPlatform.OpenGLES:             // OpenGLES on Windows
                        if (inputImageFormat.IsHDR())
                        {
                            outputFormat = inputImageFormat;
                        }
                        else if (parameters.IsSRgb)
                        {
                            outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                        }
                        else
                        {
                            switch (parameters.GraphicsProfile)
                            {
                            case GraphicsProfile.Level_9_1:
                            case GraphicsProfile.Level_9_2:
                            case GraphicsProfile.Level_9_3:
                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm;
                                break;

                            case GraphicsProfile.Level_10_0:
                            case GraphicsProfile.Level_10_1:
                            case GraphicsProfile.Level_11_0:
                            case GraphicsProfile.Level_11_1:
                            case GraphicsProfile.Level_11_2:
                                // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android
                                outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException("GraphicsProfile");
                            }
                        }
                        break;

                    default:
                        // OpenGL on Windows
                        // TODO: Need to handle OpenGL Desktop compression
                        outputFormat = parameters.IsSRgb ? PixelFormat.R8G8B8A8_UNorm_SRgb : PixelFormat.R8G8B8A8_UNorm;
                        break;
                    }
                    break;

                default:
                    throw new NotSupportedException("Platform " + parameters.Platform + " is not supported by TextureTool");
                }
                break;

            case TextureFormat.Color16Bits:
                if (parameters.IsSRgb)
                {
                    outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                }
                else
                {
                    if (alphaMode == AlphaFormat.None)
                    {
                        outputFormat = PixelFormat.B5G6R5_UNorm;
                    }
                    else if (alphaMode == AlphaFormat.Mask)
                    {
                        outputFormat = PixelFormat.B5G5R5A1_UNorm;
                    }
                }
                break;

            case TextureFormat.Color32Bits:
                if (parameters.IsSRgb)
                {
                    outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb;
                }
                break;

            case TextureFormat.AsIs:
                outputFormat = inputImageFormat;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(outputFormat);
        }
Exemplo n.º 31
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);

            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, fromSize, 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);

            // 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
            if (parameters.PremultiplyAlpha)
            {
                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 != PixelFormat.B8G8R8A8_UNorm_SRgb || (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, texImage.GetAlphaDepth());

            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);
        }
Exemplo n.º 32
0
        public void OneTimeSetUp()
        {
            var mockRecord = new Mock <IDobihRecord>();

            mockRecord.Setup(x => x.Number).Returns(Number);
            mockRecord.Setup(x => x.Name).Returns(Name);
            mockRecord.Setup(x => x.SectionCode).Returns(SectionCode);
            mockRecord.Setup(x => x.SectionName).Returns(SectionName);
            mockRecord.Setup(x => x.Country).Returns(Country);
            mockRecord.Setup(x => x.Lists).Returns(Lists);
            mockRecord.Setup(x => x.Maps1To50000).Returns(Maps1To50000);
            mockRecord.Setup(x => x.Maps1To25000).Returns(Maps1To25000);
            mockRecord.Setup(x => x.Metres).Returns(Metres);
            mockRecord.Setup(x => x.Latitude).Returns(Latitude);
            mockRecord.Setup(x => x.Longitude).Returns(Longitude);
            mockRecord.Setup(x => x.GridRef).Returns(GridRef);
            mockRecord.Setup(x => x.Drop).Returns(Drop);
            mockRecord.Setup(x => x.ColGridRef).Returns(ColGridRef);
            mockRecord.Setup(x => x.ColMetres).Returns(ColMetres);
            mockRecord.Setup(x => x.Feature).Returns(Feature);
            mockRecord.Setup(x => x.Observations).Returns(Observations);

            var mockDobihFile = new Mock <IDobihFile>();

            mockDobihFile.Setup(x => x.Records).Returns(new List <IDobihRecord> {
                mockRecord.Object
            });

            var mockIdGenerator = new Mock <IIdGenerator>();

            mockIdGenerator.Setup(x => x.Generate(Number)).Returns(Id);

            var mockCountryProvider = new Mock <IEntityProvider <Country> >();

            mockCountryProvider.Setup(x => x.GetByDobihId(Country)).Returns(new Country {
                Id = CountryId
            });

            var mockListProvider = new Mock <IEntityProvider <List> >();

            mockListProvider.Setup(x => x.GetByDobihId(List1)).Returns(new List {
                Id = List1Id
            });
            mockListProvider.Setup(x => x.GetByDobihId(List2)).Returns(new List {
                Id = List2Id
            });

            var mockSectionProvider = new Mock <IEntityProvider <Section> >();

            mockSectionProvider.Setup(x => x.GetByDobihId(SectionName)).Returns(new Section {
                Id = SectionId
            });

            var mockMapProvider = new Mock <IMapProvider>();

            mockMapProvider
            .Setup(x => x.GetMapsByCode(It.IsAny <decimal>(), It.IsAny <MapConstants.Region>(), Maps1To50000))
            .Returns(new List <Map> {
                new Map {
                    Id = Map1To50K1Id
                }, new Map {
                    Id = Map1To50K2Id
                }
            });
            mockMapProvider
            .Setup(x => x.GetMapsByCode(It.IsAny <decimal>(), It.IsAny <MapConstants.Region>(), Maps1To25000))
            .Returns(new List <Map> {
                new Map {
                    Id = Map1To25K1Id
                }, new Map {
                    Id = Map1To25K2Id
                }
            });

            var parameters = new ImportParameters
            {
                DobihFile       = mockDobihFile.Object,
                IdGenerator     = mockIdGenerator.Object,
                CountryProvider = mockCountryProvider.Object,
                ListProvider    = mockListProvider.Object,
                SectionProvider = mockSectionProvider.Object,
                MapProvider     = mockMapProvider.Object
            };

            _actual = new MountainProvider(parameters).GetAll().Single();
        }
Exemplo n.º 33
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);

            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, fromSize, 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);

            // 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
            if (parameters.PremultiplyAlpha)
                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 != PixelFormat.B8G8R8A8_UNorm_SRgb || (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, texImage.GetAlphaDepth());
            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;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Utility function to check that the texture size is supported on the graphics platform for the provided graphics profile.
        /// </summary>
        /// <param name="parameters">The import parameters</param>
        /// <param name="outputFormat">The output format</param>
        /// <param name="textureSize">The texture size requested.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>true if the texture size is supported</returns>
        /// <exception cref="System.ArgumentOutOfRangeException">graphicsProfile</exception>
        public static Size2 FindBestTextureSize(ImportParameters parameters, PixelFormat outputFormat, Size2 textureSize, ILogger logger = null)
        {
            bool isBlockCompressed =
                (outputFormat >= PixelFormat.BC1_Typeless && outputFormat <= PixelFormat.BC5_SNorm) ||
                (outputFormat >= PixelFormat.BC6H_Typeless && outputFormat <= PixelFormat.BC7_UNorm_SRgb);

            // compressed DDS files has to have a size multiple of 4.
            if ((parameters.DesiredFormat == TextureFormat.Compressed) && isBlockCompressed &&
                ((textureSize.Width % 4) != 0 || (textureSize.Height % 4) != 0))
            {
                textureSize.Width = unchecked((int)(((uint)(textureSize.Width + 3)) & ~(uint)3));
                textureSize.Height = unchecked((int)(((uint)(textureSize.Height + 3)) & ~(uint)3));
            }

            return FindMaximumTextureSize(parameters, textureSize, logger);
        }
Exemplo n.º 35
0
        public static ResultStatus ImportTextureImage(ContentManager assetManager, TextureTool textureTool, TexImage texImage, ImportParameters parameters, CancellationToken cancellationToken, Logger logger)
        {
            // Convert image to the final format
            var result = ImportTextureImageRaw(textureTool, texImage, parameters, cancellationToken, logger);

            if (result != ResultStatus.Successful)
            {
                return(result);
            }

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

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

                logger.Verbose($"Compression successful [{parameters.OutputUrl}] to ({outputImage.Description.Width}x{outputImage.Description.Height},{outputImage.Description.Format})");
            }

            return(ResultStatus.Successful);
        }