Exemplo n.º 1
0
 public static void PNG_To_DDS(string From_PNG_File, string To_DDS_File, DdsFileFormat Format)
 {
     //こっちのコードもメモリリークしていますが、GCで解放されるため放置
     System.IO.FileStream fileStream = new System.IO.FileStream(To_DDS_File, System.IO.FileMode.Create);
     DdsFile.Save(fileStream, Format, DdsErrorMetric.Perceptual, BC7CompressionMode.Slow, false, false, ResamplingAlgorithm.Bilinear, Surface.CopyFromBitmap(new Bitmap(From_PNG_File)), null);
     fileStream.Close();
 }
Exemplo n.º 2
0
        public void SaveObject(string filename, object configuration)
        {
            FileStream ddsStream = null;

            try
            {
                if (maps == null || !maps.Any())
                {
                    return;
                }

                DdsSaveConfig config = configuration as DdsSaveConfig ?? new DdsSaveConfig(FileFormat.Unknown, 0, 0, false, false);
                config.FileFormat = parsedImageFormat;

                //parse uncompressed image
                DdsFile ddsImage = new DdsFile(GetObjectStream());

                ddsStream = new FileStream(filename, FileMode.Create);
                ddsImage.Save(ddsStream, config);

                ddsStream.Close();
                ddsStream.Dispose();
            }
            finally
            {
                if (ddsStream != null)
                {
                    ddsStream.Dispose();
                }
            }
        }
Exemplo n.º 3
0
        public void GetPreview()
        {
            DdsFile dds;

            CSharpImageLibrary.ImageEngineImage image = null;
            try
            {
                this.Preview = null;
                dds          = new DdsFile(Texture, false);
                dds.Write(File.Open(System.AppDomain.CurrentDomain.BaseDirectory + "\\temp.dds", FileMode.Create, FileAccess.ReadWrite, FileShare.Read), -1);
                int maxDimension = (int)Math.Max(dds.header.width, dds.header.height);

                image        = new CSharpImageLibrary.ImageEngineImage(System.AppDomain.CurrentDomain.BaseDirectory + "\\temp.dds", maxDimension);
                Preview      = null;
                this.Preview = image.GetWPFBitmap(maxDimension, true);

                this.PreviewErrorVisibility = Visibility.Collapsed;
                OnPropertyChanged(nameof(Width));
                OnPropertyChanged(nameof(Height));
                OnPropertyChanged(nameof(TextureInfo));
            }
            catch (Exception ex)
            {
                Preview                     = null;
                this.PreviewError           = "Could not create preview! Export/Import may still work in certain circumstances." + Environment.NewLine + Environment.NewLine + ex.Message;
                this.PreviewErrorVisibility = Visibility.Visible;
            }
            finally
            {
                dds = null;
                image?.Dispose();
                image = null;
            }
        }
Exemplo n.º 4
0
        private static List <byte[]> GetMipMapData(DdsFile file)
        {
            const int     minimumWidth  = 4;
            const int     minimumHeight = 4;
            List <byte[]> mipMapDatas   = new List <byte[]>();

            byte[] data         = file.Data;
            int    dataOffset   = 0;
            int    width        = file.Header.Width;
            int    height       = file.Header.Height;
            int    depth        = file.Header.Depth == 0 ? 1 : file.Header.Depth;
            int    mipMapsCount = file.Header.Flags.HasFlag(DdsFileHeaderFlags.MipMap) ? file.Header.MipMapCount : 1;

            for (int i = 0; i < mipMapsCount; i++)
            {
                int size   = DdsPixelFormat.CalculateImageSize(file.Header.PixelFormat, width, height, depth);
                var buffer = new byte[size];
                Array.Copy(data, dataOffset, buffer, 0, size);
                mipMapDatas.Add(buffer);
                dataOffset += size;
                width       = Math.Max(width / 2, minimumWidth);
                height      = Math.Max(height / 2, minimumHeight);
            }
            return(mipMapDatas);
        }
Exemplo n.º 5
0
        private static Texture CreateTextureFromDds(
            GraphicsDevice graphicsDevice,
            DdsFile ddsFile)
        {
            var mipMapData = new TextureMipMapData[ddsFile.Header.MipMapCount];

            for (var i = 0; i < ddsFile.Header.MipMapCount; i++)
            {
                mipMapData[i] = new TextureMipMapData
                {
                    Data        = ddsFile.MipMaps[i].Data,
                    BytesPerRow = (int)ddsFile.MipMaps[i].RowPitch
                };
            }

            var width  = (int)ddsFile.Header.Width;
            var height = (int)ddsFile.Header.Height;

            // BC3 texture dimensions need to be aligned to a multiple of 4.
            if (ddsFile.ImageFormat == DdsImageFormat.Bc3)
            {
                width  = Math.Max(width, 4);
                height = Math.Max(height, 4);
            }

            return(Texture.CreateTexture2D(
                       graphicsDevice,
                       ddsFile.PixelFormat,
                       width,
                       height,
                       mipMapData));
        }
Exemplo n.º 6
0
        private string BuildMobImageSmall(ViewableMonster mob)
        {
            var iconColumnValue = mob.Icon;
            var iconName        = iconColumnValue.Substring(0, 4);

            if (listMonsters.SmallImageList.Images.ContainsKey(iconName) == false)
            {
                // [M014]010
                var iconFilename = string.Format("{0}.dds", iconName);
                var iconFilepath = Path.Combine(MobIconDir, iconFilename);
                if (File.Exists(iconFilepath))
                {
                    var dds = new DdsFile();
                    using (var stream = File.OpenRead(iconFilepath)) {
                        dds.Deserialize(stream);
                    }

                    var png = dds.AsPng();
                    listMonsters.SmallImageList.Images.Add(iconName, png);
                    listMonsters.LargeImageList.Images.Add(iconName, png);
                }
            }

            return(iconName);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Sets the DDS image for this <see cref="DDSPanel"/> from the given <paramref name="ddsfile"/>.
 /// <see cref="SupportsHSV"/> is determined from the <see cref="DdsFile.SupportsHSV"/> value.
 /// </summary>
 /// <param name="ddsfile">A <see cref="DdsFile"/> to display in this <see cref="DDSPanel"/>.</param>
 public void DDSLoad(DdsFile ddsfile)
 {
     this.ddsFile    = ddsfile;
     loaded          = true;
     this.supportHSV = ddsfile.SupportsHSV;
     ckb_CheckedChanged(null, null);
 }
Exemplo n.º 8
0
        /// <summary>
        /// Read a DdsFile and decode it
        /// </summary>
        public Image <Rgba32>[] DecodeAllMipMaps(DdsFile file)
        {
            if (IsSupportedRawFormat(file.Header.ddsPixelFormat.DxgiFormat))
            {
                var decoder = GetRawDecoder(file.Header.ddsPixelFormat.DxgiFormat);

                var images = new Image <Rgba32> [file.Header.dwMipMapCount];

                for (int mip = 0; mip < file.Header.dwMipMapCount; mip++)
                {
                    var data        = file.Faces[0].MipMaps[mip].Data;
                    var pixelWidth  = file.Faces[0].MipMaps[mip].Width;
                    var pixelHeight = file.Faces[0].MipMaps[mip].Height;

                    var image  = new Image <Rgba32>((int)pixelWidth, (int)pixelHeight);
                    var output = decoder.Decode(data, (int)pixelWidth, (int)pixelHeight);
                    var pixels = image.GetPixelSpan();

                    output.CopyTo(pixels);
                    images[mip] = image;
                }
                return(images);
            }
            else
            {
                DXGI_FORMAT format = DXGI_FORMAT.DXGI_FORMAT_UNKNOWN;
                if (file.Header.ddsPixelFormat.IsDxt10Format)
                {
                    format = file.Dxt10Header.dxgiFormat;
                }
                else
                {
                    format = file.Header.ddsPixelFormat.DxgiFormat;
                }
                IBcBlockDecoder decoder = GetDecoder(format, file.Header);

                if (decoder == null)
                {
                    throw new NotSupportedException($"This format is not supported: {format}");
                }
                var images = new Image <Rgba32> [file.Header.dwMipMapCount];

                for (int mip = 0; mip < file.Header.dwMipMapCount; mip++)
                {
                    var data        = file.Faces[0].MipMaps[mip].Data;
                    var pixelWidth  = file.Faces[0].MipMaps[mip].Width;
                    var pixelHeight = file.Faces[0].MipMaps[mip].Height;

                    var blocks = decoder.Decode(data, (int)pixelWidth, (int)pixelHeight, out var blockWidth,
                                                out var blockHeight);

                    var image = ImageToBlocks.ImageFromRawBlocks(blocks, blockWidth, blockHeight,
                                                                 (int)pixelWidth, (int)pixelHeight);

                    images[mip] = image;
                }

                return(images);
            }
        }
Exemplo n.º 9
0
        public static void importTexture(GpkExport export, string file)
        {
            var texture2d = export.Payload as Texture2D;

            var image  = new DdsFile();
            var config = new DdsSaveConfig(texture2d.GetFormat(), 0, 0, false, false);

            image.Load(file);

            if (image.MipMaps.Count == 0 || Settings.Default.GenerateMipMaps)
            {
                image.GenerateMipMaps();
            }


            texture2d.maps = new List <MipMap>();
            foreach (DdsMipMap mipMap in image.MipMaps.OrderByDescending(mip => mip.Width))
            {
                byte[] outputData = image.WriteMipMap(mipMap, config);

                var textureMipMap = new MipMap();
                textureMipMap.compFlag                     = (int)CompressionTypes.LZO;
                textureMipMap.uncompressedData             = outputData;
                textureMipMap.uncompressedSize             = outputData.Length;
                textureMipMap.uncompressedSize_chunkheader = outputData.Length;
                textureMipMap.sizeX = mipMap.Width;
                textureMipMap.sizeY = mipMap.Height;

                textureMipMap.generateBlocks();
                texture2d.maps.Add(textureMipMap);
            }
        }
Exemplo n.º 10
0
        private Texture LoadImpl(FileSystemEntry entry, GraphicsDevice graphicsDevice)
        {
            switch (Path.GetExtension(entry.FilePath).ToLowerInvariant())
            {
            case ".dds":
                if (!DdsFile.IsDdsFile(entry))
                {
                    goto case ".tga";
                }
                var ddsFile = DdsFile.FromFileSystemEntry(entry);
                return(CreateTextureFromDds(ddsFile, graphicsDevice));

            case ".tga":
                var tgaFile = TgaFile.FromFileSystemEntry(entry);
                return(CreateTextureFromTga(tgaFile, graphicsDevice));

            case ".jpg":
                using (var stream = entry.Open())
                {
                    var jpgFile = new ImageSharpTexture(stream);
                    return(CreateFromImageSharpTexture(jpgFile, graphicsDevice));
                }

            default:
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 11
0
        public static void exportTexture(GpkExport export, string file)
        {
            Texture2D image   = (Texture2D)export.Payload;
            DdsFile   ddsFile = new DdsFile();

            Task.Run(() => image.SaveObject(file, new DdsSaveConfig(image.GetFormat(), 0, 0, false, false)));
        }
Exemplo n.º 12
0
        public static DdsFile ConvertToDds(FtexFile file)
        {
            DdsFile result = new DdsFile
            {
                Header = new DdsFileHeader
                {
                    Size        = DdsFileHeader.DefaultHeaderSize,
                    Flags       = DdsFileHeaderFlags.Texture,
                    Height      = file.Height,
                    Width       = file.Width,
                    Depth       = file.Depth,
                    MipMapCount = file.MipMapCount,
                    Caps        = DdsSurfaceFlags.Texture
                }
            };

            if (result.Header.Depth == 1)
            {
                result.Header.Depth = 0;
            }
            else if (result.Header.Depth > 1)
            {
                result.Header.Flags |= DdsFileHeaderFlags.Volume;
            }

            if (result.Header.MipMapCount == 1)
            {
                result.Header.MipMapCount = 0;
            }
            else if (result.Header.MipMapCount > 1)
            {
                result.Header.Flags |= DdsFileHeaderFlags.MipMap;
                result.Header.Caps  |= DdsSurfaceFlags.MipMap;
            }

            switch (file.PixelFormatType)
            {
            case 0:
                result.Header.PixelFormat = DdsPixelFormat.DdsPfA8R8G8B8();
                break;

            case 1:
                result.Header.PixelFormat = DdsPixelFormat.DdsLuminance();
                break;

            case 2:
                result.Header.PixelFormat = DdsPixelFormat.DdsPfDxt1();
                break;

            case 4:
                result.Header.PixelFormat = DdsPixelFormat.DdsPfDxt5();
                break;

            default:
                throw new ArgumentException($"Unknown PixelFormatType {file.PixelFormatType}");
            }

            result.Data = file.Data;
            return(result);
        }
Exemplo n.º 13
0
        public override object Parse(Asset asset, BinaryReader reader, AssetImportCollection imports, AssetParseContext context)
        {
            var twelve = reader.ReadUInt32();

            if (twelve != 12)
            {
                throw new InvalidDataException();
            }

            reader.ReadUInt32(); // Length

            var ddsFile = DdsFile.FromStream(reader.BaseStream);

            var result = context.GraphicsDevice.CreateStaticTexture2D(
                ddsFile.Header.Width,
                ddsFile.Header.Height,
                ddsFile.ArraySize,
                ddsFile.MipMaps,
                ddsFile.PixelFormat,
                ddsFile.Dimension == DdsTextureDimension.TextureCube);

            result.Name = asset.Name;

            return(new Graphics.TextureAsset(result, asset));
        }
Exemplo n.º 14
0
        private void onExportedObjectSelected(ExportedObjectSelectedMessage message)
        {
            string extension = Path.GetExtension(message.Filename)?.ToLowerInvariant();

            switch (extension)
            {
            case ".ogg": {
                Task.Run(() => playSound(new FileStream(message.Filename, FileMode.Open), resetToken())).FireAndForget();

                break;
            }

            case ".dds": {
                DdsFile image = new DdsFile(message.Filename);

                viewModel.MipMaps = null;

                viewModel.Texture = image.BitmapSource;

                break;
            }

            default: {
                break;
            }
            }
        }
Exemplo n.º 15
0
        private static Image LoadDDSSquish(string name, ulong hash = 0)
        {
            Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            DdsFile dds = new DdsFile();

            // We do not have the texture present so we'll fallback to our empty default texture.
            if (!File.Exists(name))
            {
                return(RenderStorageSingleton.Instance.TextureThumbnails[0]);
            }

            using (var stream = File.Open(name, FileMode.Open))
            {
                try
                {
                    dds.Load(stream);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("Error Message when using DDS Squish: {0}", ex.Message));
                    return(LoadDDSSquish("Resources/texture.dds").GetThumbnailImage(128, 120, myCallback, IntPtr.Zero));
                }
            }
            Image Thumbnail = dds.Image().GetThumbnailImage(128, 120, myCallback, IntPtr.Zero);

            Debug.Assert(Thumbnail != null, string.Format("Thumbnail is wrong here? Trying to load: {0}", name));

            if (Thumbnail != null && hash != 0)
            {
                RenderStorageSingleton.Instance.TextureThumbnails.TryAdd(hash, Thumbnail);
            }

            return(Thumbnail);
        }
Exemplo n.º 16
0
        protected override Texture LoadEntry(FileSystemEntry entry, ContentManager contentManager, Game game, LoadOptions loadOptions)
        {
            var generateMipMaps = (loadOptions as TextureLoadOptions)?.GenerateMipMaps ?? true;

            Texture applyDebugName(Texture texture)
            {
                texture.Name = entry.FilePath;
                return(texture);
            }

            switch (Path.GetExtension(entry.FilePath).ToLower())
            {
            case ".dds":
                if (!DdsFile.IsDdsFile(entry))
                {
                    goto case ".tga";
                }
                var ddsFile = DdsFile.FromFileSystemEntry(entry);
                return(applyDebugName(CreateTextureFromDds(
                                          contentManager.GraphicsDevice,
                                          ddsFile)));

            case ".tga":
                var tgaFile = TgaFile.FromFileSystemEntry(entry);
                return(applyDebugName(CreateTextureFromTga(
                                          contentManager.GraphicsDevice,
                                          tgaFile,
                                          generateMipMaps)));

            default:
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// decode to image as an asynchronous operation.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>Image&lt;Rgba32&gt;[].</returns>
        public async Task <Image <Rgba32> > DecodeToImageAsync(DdsFile file)
        {
            Image <Rgba32> image   = null;
            var            decoder = new BcDecoder();

            if (file.Faces.Count == 6)
            {
                // Cubemap
                var right  = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[0].MipMaps[0].Data, Convert.ToInt32(file.Faces[0].Width), Convert.ToInt32(file.Faces[0].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var left   = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[1].MipMaps[0].Data, Convert.ToInt32(file.Faces[1].Width), Convert.ToInt32(file.Faces[1].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var top    = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[2].MipMaps[0].Data, Convert.ToInt32(file.Faces[2].Width), Convert.ToInt32(file.Faces[2].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var bottom = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[3].MipMaps[0].Data, Convert.ToInt32(file.Faces[3].Width), Convert.ToInt32(file.Faces[3].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var front  = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[4].MipMaps[0].Data, Convert.ToInt32(file.Faces[4].Width), Convert.ToInt32(file.Faces[4].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var back   = ColorMemoryToImage(await decoder.DecodeRaw2DAsync(file.Faces[5].MipMaps[0].Data, Convert.ToInt32(file.Faces[5].Width), Convert.ToInt32(file.Faces[5].Height), GetCompressionFormat(file, decoder.InputOptions)));
                var width  = left.Width + front.Width + right.Width + back.Width;
                var height = top.Height + front.Height + bottom.Height;
                image = new Image <Rgba32>(width, height);
                image.Mutate(i =>
                {
                    i.DrawImage(top, new Point(left.Width, 0), 1f);
                    i.DrawImage(left, new Point(0, top.Height), 1f);
                    i.DrawImage(front, new Point(left.Width, top.Height), 1f);
                    i.DrawImage(right, new Point(left.Width + front.Width, top.Height), 1f);
                    i.DrawImage(back, new Point(left.Width + front.Width + right.Width, top.Height), 1f);
                    i.DrawImage(bottom, new Point(left.Width, top.Height + front.Height), 1f);
                });
            }
            else
            {
                var bcnImage = await decoder.Decode2DAsync(file);

                image = ColorMemoryToImage(bcnImage);
            }
            return(image);
        }
Exemplo n.º 18
0
        public void SaveObject(string filename, object configuration)
        {
            if (maps == null || !maps.Any())
            {
                return;
            }

            DdsSaveConfig config = configuration as DdsSaveConfig ?? new DdsSaveConfig(FileFormat.Unknown, 0, 0, false, false);
            FileFormat    format;

            MipMap mipMap = maps.Where(mm => mm.uncompressedData != null && mm.uncompressedData.Length > 0).OrderByDescending(mm => mm.sizeX > mm.sizeY ? mm.sizeX : mm.sizeY).FirstOrDefault();

            if (mipMap == null)
            {
                return;
            }

            Stream memory = buildDdsImage(maps.IndexOf(mipMap), out format);

            if (memory == null)
            {
                return;
            }

            DdsFile    ddsImage  = new DdsFile(GetObjectStream());
            FileStream ddsStream = new FileStream(filename, FileMode.Create);

            config.FileFormat = format;
            ddsImage.Save(ddsStream, config);
            ddsStream.Close();

            memory.Close();
        }
Exemplo n.º 19
0
        public DdsFile ToDds()
        {
            DdsFile dds = new DdsFile();

            dds.width             = width; dds.height = height;
            dds.pitchOrLinearSize = byteSize;
            dds.flag        = 0xA1007;
            dds.mipMapCount = 9;
            dds.pixelFormat = new DdsPixelFormat();
            switch (type)
            {
            case TexType.RGB: dds.pixelFormat = new DdsPixelFormat(DdsPFType.RGB); break;

            case TexType.RGBA: dds.pixelFormat = new DdsPixelFormat(DdsPFType.RGBA); break;

            case TexType.DXT1: dds.pixelFormat = new DdsPixelFormat(DdsPFType.DXT1); break;

            case TexType.DXT3: dds.pixelFormat = new DdsPixelFormat(DdsPFType.DXT3); break;

            case TexType.DXT5: dds.pixelFormat = new DdsPixelFormat(DdsPFType.DXT5); break;

            case TexType.ATI2n: dds.pixelFormat = new DdsPixelFormat(DdsPFType.ATI2n); break;

            default: Console.Write("WTF, Unknown TXP type " + type + "\n"); break;
            }
            dds.caps = 0x401008;
            dds.data = data;
            return(dds);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Apply the supplied images to the areas of the base image defined by the
        /// channels in the currently loaded mask.
        /// </summary>
        /// <param name="ch1Image">The <see cref="T:System.IO.Stream"/> containing the DDS image to apply to the image when the first channel of the mask is active.</param>
        /// <param name="ch2Image">The <see cref="T:System.IO.Stream"/> containing the DDS image to apply to the image when the second channel of the mask is active.</param>
        /// <param name="ch3Image">The <see cref="T:System.IO.Stream"/> containing the DDS image to apply to the image when the third channel of the mask is active.</param>
        /// <param name="ch4Image">The <see cref="T:System.IO.Stream"/> containing the DDS image to apply to the image when the fourth channel of the mask is active.</param>
        public void ApplyImage(Stream ch1Image, Stream ch2Image, Stream ch3Image, Stream ch4Image)
        {
            if (!this.loaded || !this.MaskLoaded)
            {
                return;
            }

            DdsFile ch1dds = null, ch2dds = null, ch3dds = null, ch4dds = null;

            try
            {
                this.Enabled = false;
                Application.UseWaitCursor = true;
                Application.DoEvents();
                if (ch1Image != null)
                {
                    ch1dds = new DdsFile(); ch1dds.Load(ch1Image, false);
                }
                if (ch2Image != null)
                {
                    ch2dds = new DdsFile(); ch2dds.Load(ch2Image, false);
                }
                if (ch3Image != null)
                {
                    ch3dds = new DdsFile(); ch3dds.Load(ch3Image, false);
                }
                if (ch4Image != null)
                {
                    ch4dds = new DdsFile(); ch4dds.Load(ch4Image, false);
                }
                ddsFile.MaskedApplyImage(this.ddsMask, ch1dds, ch2dds, ch3dds, ch4dds);
            }
            finally { this.Enabled = true; Application.UseWaitCursor = false; Application.DoEvents(); }
            this.ckb_CheckedChanged(null, null);
        }
Exemplo n.º 21
0
 public static void FromDds(this TpkFile tpk, DdsFile dds)
 {
     tpk.Format      = GetTpkImageFormat(dds);
     tpk.Width       = dds.header.width;
     tpk.Height      = dds.header.height;
     tpk.MipMapCount = dds.header.mipMapCount;
     tpk.Data        = dds.bdata;
 }
Exemplo n.º 22
0
        /// <summary>
        /// Set the alpha channel of the current image from the given DDS file stream.
        /// </summary>
        /// <param name="image"><see cref="Stream"/> containing a DDS image.</param>
        public void SetAlphaFromGreyscale(Stream image)
        {
            DdsFile greyscale = new DdsFile();

            greyscale.Load(image, false);
            ddsFile.SetAlphaFromGreyscale(greyscale);
            ckb_CheckedChanged(null, null);
        }
Exemplo n.º 23
0
        private static DdsFile GenerateDds(DdsOptions options)
        {
            DdsFile ddsFile = new DdsFile();

            ddsFile.Header = new DdsFileHeader
            {
                Size        = DdsFileHeader.DefaultHeaderSize,
                Flags       = DdsFileHeaderFlags.Texture,
                Width       = options.Width,
                Height      = options.Height,
                Depth       = options.Depth,
                MipMapCount = options.MipMapCount,
                Caps        = DdsSurfaceFlags.Texture,
                PixelFormat = options.PixelFormat
            };

            if (ddsFile.Header.Depth > 1)
            {
                ddsFile.Header.Flags |= DdsFileHeaderFlags.Volume;
            }

            int mipMapCount = ddsFile.Header.MipMapCount;

            if (ddsFile.Header.MipMapCount == 1)
            {
                ddsFile.Header.MipMapCount = 0;
            }
            else if (ddsFile.Header.MipMapCount > 1)
            {
                ddsFile.Header.Flags |= DdsFileHeaderFlags.MipMap;
                ddsFile.Header.Caps  |= DdsSurfaceFlags.MipMap;
            }

            const int minimumWidth     = 4;
            const int minimumHeight    = 4;
            int       mipMapHeight     = ddsFile.Header.Height;
            int       mipMapWidth      = ddsFile.Header.Width;
            int       mipMapDepth      = ddsFile.Header.Depth == 0 ? 1 : ddsFile.Header.Depth;
            int       mipMapBufferSize = 0;

            for (int i = 0; i < mipMapCount; i++)
            {
                int mipMapSize = DdsPixelFormat.CalculateImageSize(ddsFile.Header.PixelFormat, mipMapWidth, mipMapHeight, mipMapDepth);
                mipMapBufferSize += mipMapSize;
                mipMapWidth       = Math.Max(mipMapWidth / 2, minimumWidth);
                mipMapHeight      = Math.Max(mipMapHeight / 2, minimumHeight);
            }

            ddsFile.Data = new byte[mipMapBufferSize];
            for (int i = 0; i < mipMapBufferSize; i++)
            {
                ddsFile.Data[i] = (byte)(i % 0xFF);
            }


            return(ddsFile);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Sets the DDSPanel to an unloaded state, freeing resources.
 /// </summary>
 public void Clear()
 {
     ddsFile           = new DdsFile();
     loaded            = false;
     ddsMask           = null;
     pictureBox1.Image = image = null;
     pictureBox1.Size  = (this.MaxSize == Size.Empty) ? new Size(0x80, 0x80) : Min(new Size(0x80, 0x80), this.MaxSize);
     ckb_CheckedChanged(null, null);
 }
Exemplo n.º 25
0
        public void CanReadDdsTextures()
        {
            InstalledFilesTestData.ReadFiles(".dds", _output, entry =>
            {
                var ddsFile = DdsFile.FromFileSystemEntry(entry);

                Assert.True(ddsFile.MipMaps.Length > 1);
            });
        }
 public static void CreateTexture(
     DdsFile dds,
     D3D11Device device,
     D3D11DeviceContext context,
     out D3D11Resource texture,
     out D3D11ShaderResourceView textureView)
 {
     CreateTexture(dds, device, context, 0, out texture, out textureView, out _);
 }
 public static void CreateTexture(
     DdsFile dds,
     D3D11Device device,
     D3D11DeviceContext context,
     out D3D11ShaderResourceView textureView)
 {
     CreateTexture(dds, device, context, 0, out D3D11Resource texture, out textureView, out _);
     D3D11Utils.DisposeAndNull(ref texture);
 }
Exemplo n.º 28
0
    public static DdsFile ToDds(this TpkFile tpk)
    {
        var dds = new DdsFile();

        switch (tpk.Format)
        {
        case TpkImageFormat.Bgra:     // BGRA little-endian
            dds.header.flags            |= DdsHeader.Flags.DDSD_LINEARSIZE;
            dds.header.ddspf.flags      |= DdsPixelFormat.Flags.DDPF_ALPHAPIXELS | DdsPixelFormat.Flags.DDPF_RGB;
            dds.header.ddspf.fourCC      = 0;
            dds.header.ddspf.rGBBitCount = 32;
            dds.header.ddspf.bBitMask    = 0xFF;
            dds.header.ddspf.gBitMask    = 0xFF00;
            dds.header.ddspf.rBitMask    = 0xFF0000;
            dds.header.ddspf.aBitMask    = 0xFF000000;
            dds.header.pitchOrLinearSize = tpk.Width * tpk.Height * 4;
            break;

        case TpkImageFormat.Dxt1:
            dds.header.flags            |= DdsHeader.Flags.DDSD_LINEARSIZE;
            dds.header.ddspf.flags      |= DdsPixelFormat.Flags.DDPF_FOURCC;
            dds.header.ddspf.fourCC      = BitConverter.ToUInt32(Encoding.UTF8.GetBytes("DXT1"), 0);
            dds.header.pitchOrLinearSize = Math.Max(tpk.Width * tpk.Height / 2, MinBc1LinearSize);
            break;

        case TpkImageFormat.Dxt3:
            dds.header.flags            |= DdsHeader.Flags.DDSD_LINEARSIZE;
            dds.header.ddspf.flags      |= DdsPixelFormat.Flags.DDPF_FOURCC;
            dds.header.ddspf.fourCC      = BitConverter.ToUInt32(Encoding.UTF8.GetBytes("DXT3"), 0);
            dds.header.pitchOrLinearSize = Math.Max(tpk.Width * tpk.Height, MinBc2LinearSize);
            break;

        case TpkImageFormat.Dxt5:
            dds.header.flags            |= DdsHeader.Flags.DDSD_LINEARSIZE;
            dds.header.ddspf.flags      |= DdsPixelFormat.Flags.DDPF_FOURCC;
            dds.header.ddspf.fourCC      = BitConverter.ToUInt32(Encoding.UTF8.GetBytes("DXT5"), 0);
            dds.header.pitchOrLinearSize = Math.Max(tpk.Width * tpk.Height, MinBc3LinearSize);
            break;

        default:
            throw new NotSupportedException($"Tpk format {tpk.Format} not supported.");
        }

        dds.header.width  = tpk.Width;
        dds.header.height = tpk.Height;

        if (tpk.MipMapCount > 0)
        {
            dds.header.flags      |= DdsHeader.Flags.DDSD_MIPMAPCOUNT;
            dds.header.mipMapCount = tpk.MipMapCount;
            dds.header.caps       |= DdsHeader.Caps.DDSCAPS_MIPMAP | DdsHeader.Caps.DDSCAPS_COMPLEX;
        }

        dds.bdata = tpk.Data;
        return(dds);
    }
        public static void CreateTexture(
            Stream stream,
            D3D11Device device,
            D3D11DeviceContext context,
            out D3D11ShaderResourceView textureView)
        {
            DdsFile dds = DdsFile.FromStream(stream);

            CreateTexture(dds, device, context, out textureView);
        }
        public static void CreateTexture(
            string fileName,
            D3D11Device device,
            D3D11DeviceContext context,
            out D3D11ShaderResourceView textureView)
        {
            DdsFile dds = DdsFile.FromFile(fileName);

            CreateTexture(dds, device, context, out textureView);
        }
Exemplo n.º 31
0
        protected override unsafe void OnSave( Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback )
		{
			DdsSaveConfigToken ddsToken = ( DdsSaveConfigToken )token;

			// We need to be able to feast on the goo inside..
			scratchSurface.Clear( ColorBgra.Transparent );

			using ( RenderArgs ra = new RenderArgs( scratchSurface ) )
			{
				input.Render( ra, true );
			}

			// Create the DDS file, and save it..
			DdsFile ddsFile = new DdsFile();
			ddsFile.Save( output, scratchSurface, ddsToken, callback );
		}
Exemplo n.º 32
0
        private void importTextureToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (textureTreeView.Nodes.Count == 0 || textureTreeView.SelectedNode.Index == -1)
            {
                return;
            }

            PssgNode node = ((PssgNode)textureTreeView.SelectedNode.Tag);
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Dds files|*.dds|All files|*.*";
            dialog.Title = "Select a dds file";
            dialog.FileName = node.Attributes["id"].ToString() + ".dds";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    DdsFile dds = new DdsFile(File.Open(dialog.FileName, FileMode.Open));
                    dds.Write(node);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not import texture!" + Environment.NewLine + Environment.NewLine +
                        ex.Message, "Import Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                createPreview(node);
            }
        }
Exemplo n.º 33
0
        private void exportAllTexturesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (textureTreeView.Nodes.Count == 0)
            {
                return;
            }

            try
            {
                Directory.CreateDirectory(filePath.Replace(".", "_") + "_textures");
                DdsFile dds;
                for (int i = 0; i < textureTreeView.Nodes.Count; i++)
                {
                    dds = new DdsFile(((PssgNode)textureTreeView.Nodes[i].Tag), false);
                    dds.Write(File.Open(filePath.Replace(".", "_") + "_textures" + "\\" + textureTreeView.Nodes[i].Text + ".dds", FileMode.Create), -1);
                }
                MessageBox.Show("Textures exported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("There was an error, could not export all textures!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 34
0
        private void importAllTexturesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (textureTreeView.Nodes.Count == 0)
            {
                return;
            }

            try
            {
                string directory = filePath.Replace(".", "_") + "_textures";
                if (Directory.Exists(directory) == true)
                {
                    DdsFile dds;
                    foreach (string fileName in Directory.GetFiles(directory, "*.dds"))
                    {
                        for (int i = 0; i < textureTreeView.Nodes.Count; i++)
                        {
                            if (Path.GetFileNameWithoutExtension(fileName) == textureTreeView.Nodes[i].Text)
                            {
                                dds = new DdsFile(File.Open(fileName, FileMode.Open));
                                dds.Write(((PssgNode)textureTreeView.Nodes[i].Tag));
                                break;
                            }
                        }
                    }
                    if (textureTreeView.SelectedNode != null)
                    {
                        createPreview(((PssgNode)textureTreeView.SelectedNode.Tag));
                    }
                    MessageBox.Show("Textures imported successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Could not find textures folder!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("There was an error, could not import all textures!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 35
0
 private void cubeMapImportToolStripButton_Click(object sender, EventArgs e)
 {
     if (cubeMapTreeView.Nodes.Count == 0 || cubeMapTreeView.SelectedNode.Index == -1)
     {
         return;
     }
     PssgNode node = ((PssgNode)cubeMapTreeView.SelectedNode.Tag);
     OpenFileDialog dialog = new OpenFileDialog();
     dialog.Filter = "DDS files|*.dds|All files|*.*";
     dialog.Title = "Select a cubemap dds file";
     dialog.FileName = node.Attributes["id"].ToString() + ".dds";
     dialog.Multiselect = true;
     if (dialog.ShowDialog() == DialogResult.OK)
     {
         try
         {
             DdsFile dds = new DdsFile(File.Open(dialog.FileName, FileMode.Open));
             dds.Write(node);
         }
         catch (Exception ex)
         {
             MessageBox.Show("Could not import cubemap!" + Environment.NewLine + Environment.NewLine +
                 ex.Message, "Import Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         cubeMapPictureBox.Tag = 0;
         CubeMapCreatePreview(node, 0);
     }
 }
Exemplo n.º 36
0
 private void cubeMapExportToolStripButton_Click(object sender, EventArgs e)
 {
     if (cubeMapTreeView.Nodes.Count == 0 || cubeMapTreeView.SelectedNode.Index == -1)
     {
         return;
     }
     PssgNode node = ((PssgNode)cubeMapTreeView.SelectedNode.Tag);
     SaveFileDialog dialog = new SaveFileDialog();
     dialog.Filter = "DDS files|*.dds|All files|*.*";
     dialog.Title = "Select the dds save location and file name";
     dialog.FileName = node.Attributes["id"].ToString() + ".dds";
     if (dialog.ShowDialog() == DialogResult.OK)
     {
         try
         {
             DdsFile dds = new DdsFile(node, false);
             dds.Write(File.Open(dialog.FileName, FileMode.Create), -1);
         }
         catch (Exception ex)
         {
             MessageBox.Show("Could not export cubemap!" + Environment.NewLine + Environment.NewLine +
                 ex.Message, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemplo n.º 37
0
 private void CubeMapCreatePreview(PssgNode node, int targetCount)
 {
     // Make Preview
     try
     {
         cubeMapImageLabel.Text = "";
         int height = 0; int width = 0;
         cubeMapPictureBox.Dock = DockStyle.Fill;
         height = cubeMapPictureBox.Height;
         width = cubeMapPictureBox.Width;
         FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_DDS;
         System.Drawing.Bitmap image = null;
         if (targetCount > 5)
         {
             targetCount = 0;
             cubeMapPictureBox.Tag = 0;
         }
         else
         {
             cubeMapPictureBox.Tag = targetCount;
         }
         DdsFile dds = new DdsFile(node, false);
         dds.Write(File.Open(Application.StartupPath + "\\temp.dds", FileMode.Create), targetCount);
         image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp.dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
         if (cubeMapPictureBox.Image != null)
         {
             cubeMapPictureBox.Image.Dispose();
             cubeMapPictureBox.Image = null;
         }
         /*foreach (CNode sub in node.subNodes) {
             if (targetCount == 0 && sub.attributes["typename"].ToString() == "Raw") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "Raw" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "Raw" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             } else if (targetCount == 1 && sub.attributes["typename"].ToString() == "RawNegativeX") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "RawNegativeX" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "RawNegativeX" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             } else if (targetCount == 2 && sub.attributes["typename"].ToString() == "RawPositiveY") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "RawPositiveY" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "RawPositiveY" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             } else if (targetCount == 3 && sub.attributes["typename"].ToString() == "RawNegativeY") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "RawNegativeY" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "RawNegativeY" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             } else if (targetCount == 4 && sub.attributes["typename"].ToString() == "RawPositiveZ") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "RawPositiveZ" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "RawPositiveZ" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             } else if (targetCount == 5 && sub.attributes["typename"].ToString() == "RawNegativeZ") {
                 CubeMapWriteDDS(Application.StartupPath + "\\temp" + "RawNegativeZ" + ".dds", node, targetCount);
                 image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp" + "RawNegativeZ" + ".dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
             }
         }*/
         if (image.Height <= height && image.Width <= width)
         {
             cubeMapPictureBox.Dock = DockStyle.None;
             cubeMapPictureBox.Width = image.Width;
             cubeMapPictureBox.Height = image.Height;
         }
         cubeMapPictureBox.Image = image;
     }
     catch
     {
         if (cubeMapPictureBox.Image != null)
         {
             cubeMapPictureBox.Image.Dispose();
             cubeMapPictureBox.Image = null;
         }
         cubeMapImageLabel.Text = "Could not create preview!";
         //MessageBox.Show("Could not create preview!", "No Preview", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
Exemplo n.º 38
0
 private void createPreview(PssgNode node)
 {
     // Make Preview
     try
     {
         textureImageLabel.Text = "";
         int height = 0; int width = 0;
         texturePictureBox.Dock = DockStyle.Fill;
         height = texturePictureBox.Height;
         width = texturePictureBox.Width;
         DdsFile dds = new DdsFile(node, false);
         dds.Write(File.Open(Application.StartupPath + "\\temp.dds", FileMode.Create, FileAccess.ReadWrite, FileShare.Read), -1);
         // Dispose of Old Images
         if (texturePictureBox.Image != null)
         {
             texturePictureBox.Image.Dispose();
             texturePictureBox.Image = null;
         }
         // Setup New Image
         FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_DDS;
         System.Drawing.Bitmap image = FreeImage.LoadBitmap(Application.StartupPath + "\\temp.dds", FREE_IMAGE_LOAD_FLAGS.DEFAULT, ref format);
         if (image.Height <= height && image.Width <= width)
         {
             texturePictureBox.Dock = DockStyle.None;
             texturePictureBox.Width = image.Width;
             texturePictureBox.Height = image.Height;
         }
         texturePictureBox.Image = image;
     }
     catch (Exception ex)
     {
         if (texturePictureBox.Image != null)
         {
             texturePictureBox.Image.Dispose();
             texturePictureBox.Image = null;
         }
         textureImageLabel.Text = "Could not create preview! Export/Import may still work in certain circumstances." + Environment.NewLine + Environment.NewLine + ex.Message;
         //MessageBox.Show("Could not create preview! Export/Import may still work in certain circumstances." + Environment.NewLine + Environment.NewLine
         //	+ ex.Message, "No Preview", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
     }
 }
Exemplo n.º 39
0
		protected override Document OnLoad( Stream input )
		{
			DdsFile	ddsFile	= new DdsFile();
			ddsFile.Load( input );

			BitmapLayer layer			= Layer.CreateBackgroundLayer( ddsFile.GetWidth(), ddsFile.GetHeight() );
			Surface		surface			= layer.Surface;
			ColorBgra	writeColour		= new ColorBgra();

			byte[]		readPixelData	= ddsFile.GetPixelData();

			for ( int y = 0; y < ddsFile.GetHeight(); y++ )
			{
				for ( int x = 0; x < ddsFile.GetWidth(); x++ )
				{
					int			readPixelOffset = ( y * ddsFile.GetWidth() * 4 ) + ( x * 4 );
					
					writeColour.R = readPixelData[ readPixelOffset + 0 ];
					writeColour.G = readPixelData[ readPixelOffset + 1 ];
					writeColour.B = readPixelData[ readPixelOffset + 2 ];
					writeColour.A = readPixelData[ readPixelOffset + 3 ];

					surface[ x, y ] = writeColour;
				}
			}

			// Create a document, add the surface layer to it, and return to caller.
			Document	document	= new Document( surface.Width, surface.Height );
			document.Layers.Add( layer );
			return document;
		}