Beispiel #1
0
        /// <summary>把消息头写入到流中</summary>
        /// <param name="stream"></param>
        public void Write(Stream stream)
        {
            if (!UseHeader) return;

            var writer = new BinaryWriterX(stream);
            writer.Settings.EncodeInt = true;
            writer.Write((Byte)Flag);
            if (HasFlag(Flags.Channel)) writer.Write(Channel);
            if (HasFlag(Flags.SessionID)) writer.Write(SessionID);
            if (HasFlag(Flags.Length)) writer.Write(Length);
        }
Beispiel #2
0
        private void btnSaveRaw_Click(object sender, EventArgs e)
        {
            var sfd = new SaveFileDialog
            {
                InitialDirectory = Settings.Default.LastDirectory,
                FileName         = Path.Combine(Path.GetDirectoryName(_filename), Path.GetFileNameWithoutExtension(_filename) + ".raw"),
                Filter           = "Raw Image Data (*.raw)|*.raw"
            };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var settings = new ImageSettings
            {
                Width         = (int)numWidth.Value,
                Height        = (int)numHeight.Value,
                Format        = (Format)Enum.Parse(typeof(Format), cmbFormat.SelectedValue.ToString()),
                ZOrder        = chkZOrder.Checked,
                PadToPowerOf2 = false,
                TileSize      = (int)tileSize.Value,
                Orientation   = (Cetera.Image.Orientation)Enum.Parse(typeof(Cetera.Image.Orientation), cmbOrientation.SelectedValue.ToString())
            };

            var imgSave = Common.Save((Bitmap)imbPreview.Image, settings);

            using (var bw = new BinaryWriterX(File.Create(sfd.FileName))) bw.Write(imgSave);
        }
Beispiel #3
0
        public static void Save(String filename, Bitmap bitmap)
        {
            int width  = bitmap.Width;
            int height = bitmap.Height;

            while (width % 8 != 0)
            {
                width++;
            }
            while (height % 8 != 0)
            {
                height++;
            }

            byte[] pic = Common.Save(bitmap, new ImageSettings
            {
                Width         = width,
                Height        = height,
                Orientation   = Orientation.TransposeTile,
                Format        = ImageSettings.ConvertFormat(header.imageFormat),
                PadToPowerOf2 = false
            });

            using (BinaryWriterX bw = new BinaryWriterX(File.Create(filename)))
            {
                List <short> table;
                byte[]       importPic = Deflate(pic, out table, 32, width, height);

                header.width       = (short)bitmap.Width;
                header.height      = (short)bitmap.Height;
                header.tableSize1  = table.Count * 2 + 4;
                header.tableSize2  = (header.tableSize1 + 3) & ~3;
                header.imgDataSize = importPic.Length + 4;
                bw.WriteStruct(header);

                bw.Write(header.tableSize1 << 3);
                foreach (var tableEntry in table)
                {
                    bw.Write(tableEntry);
                }

                bw.BaseStream.Position = 0x48 + header.tableSize2;
                bw.Write(header.imgDataSize << 3);
                bw.Write(importPic);
            }
        }
Beispiel #4
0
        private void WriteATR1(BinaryWriterX bw)
        {
            bw.WriteStruct(ATR1.Section);
            //bw.Write(ATR1.NumberOfAttributes);
            bw.Write(ATR1.Unknown);

            bw.WriteAlignment(_paddingChar);
        }
Beispiel #5
0
        public void Save(Stream output, ImageInfo imageInfo)
        {
            using var bw = new BinaryWriterX(output);

            var mipOffset  = HeaderSize;
            var dataOffset = 0x100;

            // Write image and mip data
            var mipOffsets = new List <int> {
                dataOffset
            };

            var dataPosition = dataOffset;

            output.Position = dataPosition;
            bw.Write(imageInfo.ImageData);
            dataPosition += imageInfo.ImageData.Length;

            if (imageInfo.MipMapCount > 0)
            {
                foreach (var mipData in imageInfo.MipMapData)
                {
                    mipOffsets.Add(dataPosition);
                    bw.Write(mipData);
                    dataPosition += mipData.Length;
                }
            }

            // Write mip offsets
            output.Position = mipOffset;
            bw.WriteMultiple(mipOffsets.Select(x => x - dataOffset));

            // Write unknown data
            bw.Write(_unkData);

            // Write header
            _header.mipMapCount      = imageInfo.MipMapCount;
            _header.format           = imageInfo.ImageFormat;
            _header.width            = imageInfo.ImageSize.Width;
            _header.height           = imageInfo.ImageSize.Height;
            _header.textureDataSize  = (int)(output.Length - dataOffset);
            _header.textureDataSize2 = (int)(output.Length - dataOffset);

            output.Position = 0;
            bw.WriteType(_header);
        }
Beispiel #6
0
        // TODO: Set firstBlockLength again (need to understand enough ZLib for that)
        public void Save(Stream output, IList <IArchiveFileInfo> files)
        {
            using var bw = new BinaryWriterX(output);
            var castedFiles = files.Cast <X3ArchiveFileInfo>().ToArray();

            var header = new X3Header
            {
                fileCount = files.Count
            };

            // Write files
            bw.BaseStream.Position = (HeaderSize + 4 + files.Count * EntrySize + header.offsetMultiplier - 1) & ~(header.offsetMultiplier - 1);

            foreach (var file in castedFiles)
            {
                var fileOffset = bw.BaseStream.Position;

                if (file.Entry.IsCompressed)
                {
                    // Write prefix information when compressed
                    bw.Write((uint)file.FileSize);
                    bw.Write(file.FirstBlockSize);
                }

                var writtenSize = file.SaveFileData(bw.BaseStream);
                bw.WriteAlignment(header.offsetMultiplier);

                file.Entry.offset   = fileOffset / header.offsetMultiplier;
                file.Entry.fileSize = (int)writtenSize;
                if (file.Entry.IsCompressed)
                {
                    file.Entry.decompressedFileSize = (int)file.FileSize;
                }
            }

            // Write file entries
            bw.BaseStream.Position = HeaderSize + 4;
            foreach (var file in castedFiles)
            {
                bw.WriteType(file.Entry);
            }

            // Write header
            bw.BaseStream.Position = 0;
            bw.WriteType(header);
        }
Beispiel #7
0
        public static void WriteMultiple <T>(this BinaryWriterX bw, IEnumerable <T> list)
        {
            if (list.Count() <= 0)
            {
                bw.Write(0);
                return;
            }

            var ms = new MemoryStream();

            using (var bwIntern = new BinaryWriterX(ms, true))
                foreach (var t in list)
                {
                    bwIntern.WriteStruct(t);
                }
            bw.Write(ms.ToArray());
        }
Beispiel #8
0
        public void Save(string filename)
        {
            //Update nameOffsets
            List <NameEntry> redNames = new List <NameEntry>();
            int nameOffset            = 0;

            foreach (var file in Files)
            {
                if (redNames.Find(n => n.name.Equals(file.FileName)) == null)
                {
                    file.entry.relNameOffset = (short)nameOffset;

                    redNames.Add(new NameEntry
                    {
                        name   = file.FileName,
                        offset = nameOffset
                    });
                    nameOffset += Encoding.ASCII.GetByteCount(file.FileName) + 1;
                }
                else
                {
                    file.entry.relNameOffset = (short)redNames.Find(n => n.name.Equals(file.FileName)).offset;
                }
            }

            var dataOffset = 0x10 + Files.Count * 0xe + ((nameOffset + 3) & ~3);

            using (var bw = new BinaryWriterX(File.Create(filename)))
            {
                //Update fileMeta and write FileData
                bw.BaseStream.Position = dataOffset;
                int absDataOffset = dataOffset;
                foreach (var file in Files)
                {
                    absDataOffset = file.Write(bw.BaseStream, absDataOffset);
                }

                //Write Entries and Names
                bw.BaseStream.Position = 0x10;
                foreach (var file in Files)
                {
                    bw.WriteStruct(file.entry);
                }
                foreach (var nameEntry in redNames)
                {
                    bw.Write(Encoding.ASCII.GetBytes(nameEntry.name + "\0"));
                }
                bw.WriteAlignment(4, 0xff);

                //Write Header
                header.fileEntryCount           = (short)Files.Count;
                header.fileEntryCountMultiplier = 1;
                header.fileEntryCountDerived    = (short)(header.fileEntryCount / header.fileEntryCountMultiplier);
                header.metaSecSize     = dataOffset;
                bw.BaseStream.Position = 0;
                bw.WriteStruct(header);
            }
        }
Beispiel #9
0
        public void Save(string filename)
        {
            var sjis = Encoding.GetEncoding("SJIS");

            //Update TextOffsets
            int textOffset = 0;
            int labelCount = 0;
            int pageCount  = 0;

            for (int j = 0; j < entries.Count; j++)
            {
                if (labelCount < Labels.Count && Labels[labelCount].Text.Length >= 4 && Labels[labelCount].Text.Substring(0, 4) == "<NP>")
                {
                    pageCount = 0;
                }
                for (int i = 0; i < entries[j].metaInfo.Count; i++)
                {
                    var meta = entries[j].metaInfo[i];
                    if (meta.type == 1 && i == 1 && entries[j].metaInfo.Count(m => m.type == 0) > 0)
                    {
                        entries[j].metaInfo[i].value = pageCount++;
                    }
                    if (meta.type == 0)
                    {
                        entries[j].metaInfo[i].value = (Labels[labelCount].Text == String.Empty) ? -1 : textOffset;
                        textOffset += (Labels[labelCount].Text == String.Empty) ? 0 : sjis.GetByteCount(Labels[labelCount].Text.Replace("<NP>", "").TrimEnd('\n')) + 1;
                        labelCount++;
                    }
                }
            }

            using (var bw = new BinaryWriterX(File.Create(filename)))
            {
                //Write Texts
                bw.BaseStream.Position = cfgHeader.dataOffset;
                foreach (var label in Labels)
                {
                    if (label.Text != String.Empty)
                    {
                        bw.Write(sjis.GetBytes(label.Text.Replace("<NP>", "").TrimEnd('\n') + "\0"));
                    }
                }
                cfgHeader.dataLength = (uint)bw.BaseStream.Position - cfgHeader.dataOffset;
                bw.WriteAlignment(16, 0xff);

                //Write Entries
                bw.BaseStream.Position = 0x10;
                foreach (var entry in entries)
                {
                    entry.Write(bw.BaseStream);
                }
                bw.WriteAlignment(16, 0xff);

                //Write Header
                bw.BaseStream.Position = 0;
                bw.WriteStruct(cfgHeader);
            }
        }
Beispiel #10
0
        public static void Save(string filename, Bitmap bitmap)
        {
            int width  = (bitmap.Width + 0x7) & ~0x7;
            int height = (bitmap.Height + 0x7) & ~0x7;

            var settings = new ImageSettings
            {
                Width         = width,
                Height        = height,
                Format        = ImageSettings.ConvertFormat(header.imageFormat),
                PadToPowerOf2 = false,
                ZOrder        = false
            };

            byte[] pic = Common.Save(bitmap, settings);

            using (var bw = new BinaryWriterX(File.Create(filename)))
            {
                //Header
                header.bitDepth = 32;
                header.width    = (short)width;
                header.height   = (short)height;

                //tile table
                List <short> table;
                byte[]       importPic = Deflate(pic, out table);

                header.width       = (short)bitmap.Width;
                header.height      = (short)bitmap.Height;
                header.tableSize1  = table.Count * 2 + 4;
                header.tableSize2  = (header.tableSize1 + 3) & ~3;
                header.imgDataSize = importPic.Length + 4;
                bw.WriteStruct(header);

                bw.Write(header.tableSize1 << 3);
                foreach (var tableEntry in table)
                {
                    bw.Write(tableEntry);
                }

                bw.BaseStream.Position = 0x48 + header.tableSize2;
                bw.Write(header.imgDataSize << 3);
                bw.Write(importPic);
            }
        }
Beispiel #11
0
        public byte[] Deflate(byte[] pic, int bpp, out MemoryStream table)
        {
            table = new MemoryStream();
            using (var tableB = new BinaryWriterX(table, true))
            {
                if (entryStart != null)
                {
                    tableB.Write(entryStart);
                }

                List <byte[]> parts = new List <byte[]>();

                using (var picB = new BinaryReaderX(new MemoryStream(pic)))
                    while (picB.BaseStream.Position < picB.BaseStream.Length)
                    {
                        byte[] part = picB.ReadBytes(64 * bpp / 8);

                        if (parts.Find(x => x.SequenceEqual(part)) != null)
                        {
                            if (entryStart != null)
                            {
                                tableB.Write(parts.FindIndex(x => x.SequenceEqual(part)));
                            }
                            else
                            {
                                tableB.Write((short)parts.FindIndex(x => x.SequenceEqual(part)));
                            }
                        }
                        else
                        {
                            if (entryStart != null)
                            {
                                tableB.Write(parts.Count);
                            }
                            else
                            {
                                tableB.Write((short)parts.Count);
                            }
                            parts.Add(part);
                        }
                    }

                return(parts.SelectMany(x => x.SelectMany(b => new[] { b })).ToArray());
            }
        }
Beispiel #12
0
        public static void Save(string filename, Bitmap bitmap)
        {
            int width  = (bitmap.Width + 0x7) & ~0x7;
            int height = (bitmap.Height + 0x7) & ~0x7;

            var settings = new ImageSettings
            {
                Width         = width,
                Height        = height,
                Orientation   = Orientation.TransposeTile,
                Format        = ImageSettings.ConvertFormat(header.imageFormat),
                PadToPowerOf2 = false
            };

            byte[] pic = Common.Save(bitmap, settings);

            using (var bw = new BinaryWriterX(File.Create(filename)))
            {
                //Header
                header.width  = (short)bitmap.Width;
                header.height = (short)bitmap.Height;

                //tile table
                var    table     = new MemoryStream();
                byte[] importPic = Deflate(pic, ImageSettings.ConvertFormat(header.imageFormat), out table);

                //Table
                bw.BaseStream.Position = 0x48;
                var comp = Level5.Compress(table, tableComp);
                bw.Write(comp);
                header.tableSize1 = comp.Length + 4;
                header.tableSize2 = (header.tableSize1 + 3) & ~3;

                //Image
                bw.BaseStream.Position = 0x48 + header.tableSize2;
                header.imageFormat     = (editMode) ? Format.ETC1 : header.imageFormat;
                comp = Level5.Compress(new MemoryStream(importPic), picComp);
                bw.Write(comp);
                header.imgDataSize = comp.Length;

                //Header
                bw.BaseStream.Position = 0;
                bw.WriteStruct(header);
            }
        }
Beispiel #13
0
        public void Save(string filename)
        {
            using (var bw = new BinaryWriterX(File.OpenWrite(filename)))
            {
                //preData
                bw.Write(preData);

                //Entries (literally all other data)
                foreach (var label in Labels)
                {
                    bw.Write(label.textEntry.ident);
                    bw.Write(label.textEntry.inlineData);

                    var byteText = Encoding.UTF8.GetBytes(label.Text);
                    var byteSize = ((byteText.Length + 1) % 2 == 1) ? byteText.Length + 2 : byteText.Length + 1;

                    bw.Write((ushort)(byteSize / 2));
                    bw.Write(byteText);
                    bw.Write((byte)0);
                    bw.WriteAlignment(2);

                    bw.Write(label.textEntry.postData);
                }
            }
        }
Beispiel #14
0
        public void Save(string filename)
        {
            using (BinaryWriterX bw = new BinaryWriterX(File.OpenWrite(filename)))
            {
                var sjis = Encoding.GetEncoding("SJIS");

                //Update entries
                uint relOffset = 0;
                var  count     = 1;
                foreach (var label in Labels)
                {
                    if (count < offsets.Count)
                    {
                        uint byteCount = (uint)sjis.GetByteCount(label.Text.Replace("\n", "\\n").Replace("\xa", "\\n")) + 1;

                        foreach (var entry in entries)
                        {
                            foreach (var data in entry.data)
                            {
                                if (data.type == 0 && data.value == offsets[count])
                                {
                                    data.value = relOffset + byteCount;
                                }
                            }
                        }

                        relOffset += byteCount;
                        count++;
                    }
                }

                //Header
                header.stringSecSize = (int)(relOffset + 0xf) & ~0xf;
                bw.WriteStruct(header);

                //Entries
                foreach (var entry in entries)
                {
                    bw.Write(entry.entryTypeID);
                    bw.Write(entry.entryLength);
                    bw.Write(entry.typeMask);
                    foreach (var data in entry.data)
                    {
                        bw.Write(data.value);
                    }
                }
                bw.WriteAlignment(0x10, 0xff);

                //Text
                foreach (var label in Labels)
                {
                    bw.Write(sjis.GetBytes(label.Text.Replace("\n", "\\n").Replace("\xa", "\\n")));
                    bw.Write((byte)0);
                }
                bw.WriteAlignment(0x10, 0xff);

                //Signature
                bw.Write(sig);
            }
        }
Beispiel #15
0
        public void Save(string filename)
        {
            //check original sizes
            int bmpCount = 0;

            foreach (var txobj in TxObs)
            {
                for (int j = 0; j < ((txobj.mipmapLvls == 0) ? 1 : txobj.mipmapLvls); j++)
                {
                    if (bmps[bmpCount].Width != txobj.width / (1 << j) || bmps[bmpCount].Height != txobj.height / (1 << j))
                    {
                        throw new Exception($"Image {bmpCount:00} has to be {txobj.width / (1 << j)}x{txobj.height / (1 << j)}px!");
                    }
                    bmpCount++;
                }
            }

            using (var bw = new BinaryWriterX(File.OpenWrite(filename)))
            {
                bw.Write(list);

                bmpCount = 0;
                for (int i = 0; i < TxObs.Count; i++)
                {
                    bw.BaseStream.Position = TxObs[i].texDataOffset;
                    var width  = TxObs[i].width;
                    var height = TxObs[i].height;
                    for (int j = 0; j < ((TxObs[i].mipmapLvls == 0) ? 1 : TxObs[i].mipmapLvls); j++)
                    {
                        var settings = new ImageSettings
                        {
                            Width   = (int)width,
                            Height  = (int)height,
                            Format  = Support.CTRFormat[(byte)TxObs[i].format],
                            Swizzle = new CTRSwizzle((int)width, (int)height)
                        };

                        bw.Write(Common.Save(bmps[bmpCount++], settings));

                        width  /= 2;
                        height /= 2;
                    }
                }
            }
        }
Beispiel #16
0
        public void Save(Stream output)
        {
            using (var bw = new BinaryWriterX(output))
            {
                var dataOffset = entries[0].offset;

                foreach (var file in Files)
                {
                    bw.Write(dataOffset);

                    file.Write(bw.BaseStream, dataOffset);

                    dataOffset = (uint)bw.BaseStream.Length;
                }

                bw.Write(dataOffset);
            }
        }
Beispiel #17
0
        public void Save(Stream output)
        {
            using (var bw = new BinaryWriterX(output))
            {
                //Header
                bw.WriteStruct(partHeader);
                bw.WriteStruct(header);

                //Files
                bw.BaseStream.Position = Files[0].entry.offset;
                foreach (var file in Files)
                {
                    file.entry.offset = (uint)bw.BaseStream.Position;
                    file.entry.size   = (uint)file.FileSize;

                    bw.WriteAlignment();
                    file.FileData.CopyTo(bw.BaseStream);
                }

                //Entries
                bw.BaseStream.Position = header.entryListOffset;
                foreach (var file in Files)
                {
                    bw.WriteStruct(file.entry);
                }

                //NameLength
                bw.BaseStream.Position = header.nameOffset;
                var nameOffset = (uint)bw.BaseStream.Length;
                foreach (var file in Files)
                {
                    bw.Write(nameOffset);
                    nameOffset += (uint)Encoding.ASCII.GetByteCount(file.FileName) + 1;
                }

                //Names
                bw.BaseStream.Position = bw.BaseStream.Length;
                foreach (var file in Files)
                {
                    bw.WriteASCII(file.FileName);
                    bw.Write((byte)0);
                }
            }
        }
Beispiel #18
0
        public void Save(String filename)
        {
            Color[] colors      = TmxSupport.GetPalette(bmp);
            byte[]  picData     = null;
            byte[]  paletteData = null;

            if (colors.Length == 16)
            {
                picData     = TmxSupport.CreateIndexed4(bmp, colors);
                paletteData = TmxSupport.GetPaletteBytes(colors);

                header.imageFormat   = TMXPixelFormat.PSMT4;
                header.paletteFormat = TMXPixelFormat.PSMCT32;
            }
            else if (colors.Length == 256)
            {
                picData     = TmxSupport.CreateIndexed8(bmp, colors);
                paletteData = TmxSupport.GetPaletteBytes(colors);

                header.imageFormat   = TMXPixelFormat.PSMT8;
                header.paletteFormat = TMXPixelFormat.PSMCT32;
            }
            else
            {
                picData = TmxSupport.Create32(bmp);

                header.imageFormat = TMXPixelFormat.PSMCT32;
            }

            header.height = (ushort)bmp.Height;
            header.width  = (ushort)bmp.Width;

            using (BinaryWriterX bw = new BinaryWriterX(File.Create(filename)))
            {
                bw.WriteStruct(header);
                bw.WriteASCII(comment);
                bw.BaseStream.Position = 0x40;
                if (paletteData != null)
                {
                    bw.Write(paletteData);
                }
                bw.Write(picData);
            }
        }
Beispiel #19
0
        private void WriteLBL1(BinaryWriterX bw)
        {
            // Calculate Section Size
            uint newSize = sizeof(uint); // Number of Groups

            newSize           = LBL1.Groups.Aggregate(newSize, (current, grp) => current + sizeof(uint) + sizeof(uint));
            newSize           = LBL1.Labels.Aggregate(newSize, (current, lbl) => current + (uint)(sizeof(byte) + lbl.Name.Length + sizeof(uint)));
            LBL1.Section.Size = newSize;

            // Calculate Group Offsets
            uint runningTotal = 0;

            for (var i = 0; i < LBL1.Groups.Count; i++)
            {
                LBL1.Groups[i].Offset = LBL1.NumberOfGroups * sizeof(uint) * 2 + sizeof(uint) + runningTotal;
                runningTotal          = LBL1.Labels.Where(lbl => lbl.Checksum == i).Aggregate(runningTotal, (current, lbl) => current + (uint)(sizeof(byte) + lbl.Name.Length + sizeof(uint)));
            }

            // Section
            bw.WriteStruct(LBL1.Section);
            bw.Write(LBL1.NumberOfGroups);

            // Groups
            foreach (var group in LBL1.Groups)
            {
                bw.WriteStruct(group);
            }

            // Labels
            foreach (var group in LBL1.Groups)
            {
                foreach (var label in LBL1.Labels)
                {
                    if (label.Checksum == LBL1.Groups.IndexOf(group))
                    {
                        bw.Write(Convert.ToByte(Encoding.ASCII.GetBytes(label.Name).Length));
                        bw.WriteASCII(label.Name);
                        bw.Write(label.Index);
                    }
                }
            }

            bw.WriteAlignment(_paddingChar);
        }
Beispiel #20
0
        private void WriteEntries(DdtFileEntry parent, BinaryWriterX bwDdt, BinaryWriterX bwImg, ref int runningFileIndex)
        {
            var subEntryCount = -parent.SubEntryCountOrFileSize;

            for (var i = 0; i < subEntryCount; i++)
            {
                var entry = parent.SubEntries[i];
                bwDdt.Write(entry.PathOffset);
                bwDdt.Write(entry.NextDirectoryOffsetOrFileOffset);
                bwDdt.Write(entry.SubEntryCountOrFileSize);
            }

            for (var i = 0; i < subEntryCount; i++)
            {
                // TODO: Adjust parent.SubEntries[i].PathOffset if we ever allow changes to the directory tree
                //bw.BaseStream.Position = parent.SubEntries[i].PathOffset;
                bwDdt.Write(Encoding.GetEncoding("EUC-JP").GetBytes(parent.SubEntries[i].Name));
                bwDdt.Write((byte)0x0);
            }
            bwDdt.WriteAlignment(4);

            for (var i = 0; i < subEntryCount; i++)
            {
                var entry = parent.SubEntries[i];

                if (entry.SubEntryCountOrFileSize >= 0)
                {
                    var fileInfo = Files[runningFileIndex];
                    fileInfo.FileData.CopyTo(bwImg.BaseStream);
                    bwImg.WriteAlignment((int)Alignment);
                    runningFileIndex++;
                }
            }

            for (var i = 0; i < subEntryCount; i++)
            {
                var entry = parent.SubEntries[i];

                if (entry.SubEntryCountOrFileSize < 0)
                {
                    WriteEntries(entry, bwDdt, bwImg, ref runningFileIndex);
                }
            }
        }
Beispiel #21
0
        public void Save(string filename)
        {
            int width              = (Image.Width + 0x7) & ~0x7;
            int height             = (Image.Height + 0x7) & ~0x7;
            var isBlockCompression = Support.Format[header.imageFormat].FormatName.Contains("DXT");
            var settings           = new ImageSettings
            {
                Width   = width,
                Height  = height,
                Format  = Support.Format[header.imageFormat],
                Swizzle = isBlockCompression ? new Support.BlockSwizzle(header.width, header.height) : null
            };

            byte[] pic = Kontract.Image.Common.Save(Image, settings);

            using (var bw = new BinaryWriterX(File.Create(filename)))
            {
                //Header
                header.width  = (short)Image.Width;
                header.height = (short)Image.Height;

                //tile table
                var    table     = new MemoryStream();
                byte[] importPic = Deflate(pic, Support.Format[header.imageFormat].BitDepth, out table);

                //Table
                bw.BaseStream.Position = 0x48;
                var comp = Level5.Compress(table, tableComp);
                bw.Write(comp);
                header.tableSize1 = comp.Length;
                header.tableSize2 = (header.tableSize1 + 3) & ~3;

                //Image
                bw.BaseStream.Position = 0x48 + header.tableSize2;
                comp = Level5.Compress(new MemoryStream(importPic), picComp);
                bw.Write(comp);
                bw.WriteAlignment(4);
                header.imgDataSize = comp.Length;

                //Header
                bw.BaseStream.Position = 0;
                bw.WriteStruct(header);
            }
        }
Beispiel #22
0
        public void Save(Stream file)
        {
            int width    = (Image.Width + 0x7) & ~0x7;
            int height   = (Image.Height + 0x7) & ~0x7;
            var settings = new ImageSettings
            {
                Width   = width,
                Height  = height,
                Format  = Support.Format[header.imageFormat],
                Swizzle = new ImgcSwizzle(width, height)
            };

            byte[] pic = L5XFEditor.Image.Common.Save(Image, settings);

            using (var bw = new BinaryWriterX(file, true))
            {
                //Header
                header.width  = (short)Image.Width;
                header.height = (short)Image.Height;

                //tile table
                var    table     = new MemoryStream();
                byte[] importPic = Deflate(pic, Support.Format[header.imageFormat].BitDepth, out table);

                //Table
                bw.BaseStream.Position = 0x48;
                var comp = Level5.Compress(table, tableComp);
                bw.Write(comp);
                header.tableSize1 = comp.Length;
                header.tableSize2 = (header.tableSize1 + 3) & ~3;

                //Image
                bw.BaseStream.Position = 0x48 + header.tableSize2;
                header.imageFormat     = (editMode) ? (byte)28 : header.imageFormat;
                comp = Level5.Compress(new MemoryStream(importPic), picComp);
                bw.Write(comp);
                bw.WriteAlignment(4);
                header.imgDataSize = comp.Length;

                //Header
                bw.BaseStream.Position = 0;
                bw.WriteStruct(header);
            }
        }
Beispiel #23
0
        public void Save(Stream output, bool leaveOpen = false)
        {
            using (var bw = new BinaryWriterX(output, leaveOpen))
            {
                //SARCHeader
                var header = new SARCHeader {
                    dataOffset = Files.Aggregate(40 + Files.Sum(afi => usesSFNT ? afi.FileName.Length / 4 * 4 + 20 : 16), (n, afi) => Pad(n, afi.FileName))
                };
                bw.WriteStruct(header); // filesize is added later

                //SFATHeader
                bw.WriteStruct(new SFATHeader {
                    nodeCount = (short)Files.Count
                });

                //SFAT List + nameList
                int nameOffset = 0;
                int dataOffset = 0;
                foreach (var afi in Files)
                {
                    dataOffset = Pad(dataOffset, afi.FileName);
                    var fileLen   = (int)afi.FileData.Length;
                    var sfatEntry = new SFATEntry
                    {
                        nameHash      = usesSFNT ? SimpleHash.Create(afi.FileName, 0x65) : Convert.ToUInt32(afi.FileName.Substring(2, 8), 16),
                        SFNTOffset    = (short)(usesSFNT ? nameOffset : 0),
                        filenameFlags = (short)(usesSFNT ? 0x100 : 0),
                        dataStart     = dataOffset,
                        dataEnd       = dataOffset + fileLen
                    };
                    bw.WriteStruct(sfatEntry);
                    nameOffset += afi.FileName.Length / 4 + 1;
                    dataOffset  = sfatEntry.dataEnd;
                }

                bw.WriteStruct(new SFNTHeader());
                if (usesSFNT)
                {
                    foreach (var afi in Files)
                    {
                        bw.WriteASCII(afi.FileName.PadRight(afi.FileName.Length / 4 * 4 + 4, '\0'));
                    }
                }

                bw.WriteAlignment(header.dataOffset);
                foreach (var afi in Files)
                {
                    bw.Write(new byte[Pad((int)bw.BaseStream.Length, afi.FileName) - (int)bw.BaseStream.Length]); // padding
                    afi.FileData.CopyTo(bw.BaseStream);
                }

                bw.BaseStream.Position = 0;
                header.fileSize        = (int)bw.BaseStream.Length;
                bw.WriteStruct(header);
            }
        }
Beispiel #24
0
        public void Write(Stream output, long offset, ByteOrder byteOrder)
        {
            using (var bw = new BinaryWriterX(output, true, byteOrder))
            {
                if (System == Platform.Switch)
                {
                    SwitchMetadata.Offset = (int)offset;
                }
                else
                {
                    Metadata.Offset = (int)offset;
                }

                if (State == ArchiveFileState.Archived)
                {
                    base.FileData.CopyTo(bw.BaseStream);
                }
                else
                {
                    if (CompressionLevel != CompressionLevel.NoCompression)
                    {
                        var bytes = ZLib.Compress(FileData, CompressionLevel, true);
                        bw.Write(bytes);
                        if (System == Platform.Switch)
                        {
                            SwitchMetadata.CompressedSize = bytes.Length;
                        }
                        else
                        {
                            Metadata.CompressedSize = bytes.Length;
                        }
                    }
                    else
                    {
                        FileData.CopyTo(bw.BaseStream);
                        if (System == Platform.Switch)
                        {
                            SwitchMetadata.CompressedSize = (int)FileData.Length;
                        }
                        else
                        {
                            Metadata.CompressedSize = (int)FileData.Length;
                        }
                    }

                    if (System == Platform.Switch)
                    {
                        SwitchMetadata.UncompressedSize = (int)FileData.Length;
                    }
                    else
                    {
                        Metadata.UncompressedSize = System == Platform.CTR ? (int)(FileData.Length & 0x00FFFFFF) : (int)(FileData.Length << 3);
                    }
                }
            }
        }
Beispiel #25
0
        public void Save(Stream output, ImageInfo imageInfo)
        {
            using var bw = new BinaryWriterX(output);

            // Calculate offsets
            var nameOffset    = HeaderSize;
            var dataOffset    = (nameOffset + imageInfo.Name.Length + 0x10) & ~0xF; // 0x10 = 0x1 + 0xF
            var paletteOffset = (dataOffset + imageInfo.ImageData.Length + (imageInfo.MipMapData?.Sum(x => x.Length) ?? 0) + 0x3F) & ~0x3F;

            // Write name
            output.Position = nameOffset;
            bw.WriteString(imageInfo.Name, Encoding.ASCII, false);

            // Write image data
            output.Position = dataOffset;
            bw.Write(imageInfo.ImageData);

            // Write mip levels
            foreach (var mipData in imageInfo.MipMapData)
            {
                bw.Write(mipData);
            }

            // Write palette data
            if (imageInfo.HasPaletteInformation)
            {
                output.Position = paletteOffset;
                bw.Write(imageInfo.PaletteData);
            }

            // Update header
            _header.nameOffset    = nameOffset;
            _header.dataOffset    = dataOffset;
            _header.paletteOffset = paletteOffset;
            _header.mipLevels     = (byte)imageInfo.MipMapCount;
            _header.format        = (byte)imageInfo.ImageFormat;
            _header.width         = (short)imageInfo.ImageSize.Width;
            _header.height        = (short)imageInfo.ImageSize.Height;

            // Write header
            output.Position = 0;
            bw.WriteType(_header);
        }
Beispiel #26
0
        public static byte[] Compress(Stream input)
        {
            using (var br = new BinaryReaderX(input))
            {
                var inputArr = br.ReadAllBytes();

                (var rleScan, var lzScan) = Prescan(inputArr);
                ProcessPrescans(ref rleScan, lzScan);

                //Replace compression areas
                List <(int rangeStart, int count, int compressedSize, int method)> merge = rleScan.Select(e => (e.rangeStart, e.count, e.compressedSize, 0)).ToList();
                merge.AddRange(lzScan.Select(e => (e.rangeStart, e.count, e.compressedSize, 1)));
                merge = merge.OrderBy(e => e.rangeStart).ToList();

                var ms = new MemoryStream();
                ms.Position = 0xc;
                using (var bw = new BinaryWriterX(ms, true))
                {
                    foreach (var m in merge)
                    {
                        WriteUncompressedData(bw.BaseStream, br.ReadBytes(m.rangeStart - (int)br.BaseStream.Position));
                        if (m.method == 0)
                        {
                            WriteRLEData(bw.BaseStream, m.count, br.ReadByte());
                            br.BaseStream.Position += m.count - 1;
                        }
                        else
                        {
                            WriteLZData(bw.BaseStream, GetMaxOccurence(inputArr, m.rangeStart));
                            br.BaseStream.Position += m.count;
                        }
                    }
                    WriteUncompressedData(bw.BaseStream, br.ReadBytes((int)(br.BaseStream.Length - br.BaseStream.Position)));

                    bw.BaseStream.Position = 0;
                    bw.Write(0xa755aafc);
                    bw.Write((int)br.BaseStream.Length);
                    bw.Write((int)bw.BaseStream.Length);
                }

                return(ms.ToArray());
            }
        }
Beispiel #27
0
        public void Save(String filename)
        {
            using (BinaryWriterX bw = new BinaryWriterX(File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Write)))
            {
                List <List <ushort> > chars = new List <List <ushort> >();
                for (int i = 0; i < Labels.Count; i++)
                {
                    List <ushort> list = new List <ushort>();
                    for (int j = 0; j < Labels[i].Text.Length; j++)
                    {
                        list.Add(Labels[i].Text[j]);
                    }
                    chars.Add(list);
                }

                //Header
                bw.WriteASCII("MSGD");
                bw.Write(header.unk1);
                bw.Write(header.unk2);
                bw.Write(Labels.Count);
                bw.Write(0x20);

                //write offsetlist
                bw.BaseStream.Position = 0x20; int offset = 0;
                for (int i = 0; i < chars.Count; i++)
                {
                    bw.Write(offset);
                    offset += chars[i].Count * 2 + 2;
                }

                //pad to next 0x10
                while (bw.BaseStream.Position % 16 != 0)
                {
                    bw.BaseStream.Position += 1;
                }

                //write dataOffset
                long bk = bw.BaseStream.Position;
                bw.BaseStream.Position = 0x14;
                bw.Write((int)bk);
                bw.BaseStream.Position = bk;

                //write obfuscated text
                for (int i = 0; i < chars.Count; i++)
                {
                    for (int j = 0; j < chars[i].Count; j++)
                    {
                        bw.Write((ushort)(chars[i][j] ^ 0xff73));
                    }
                    bw.Write((ushort)0xff73);
                }
            }
        }
Beispiel #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="output"></param>
 public void Save(Stream output)
 {
     using (var bw = new BinaryWriterX(output, true))
     {
         _content.CharacterCount    = (short)Entries.First().EditedText.Trim().Length;
         _content.CharacterDataSize = (short)Encoding.UTF8.GetByteCount(Entries.First().EditedText);
         bw.WriteType(_content);
         bw.Write((byte)0x0);
     }
 }
Beispiel #29
0
        public async void Save(IFileSystem fileSystem, UPath savePath)
        {
            using var archiveBw = new BinaryWriterX(await fileSystem.OpenFileAsync(savePath, FileMode.Create, FileAccess.ReadWrite));
            using var indexBw   = new BinaryWriterX(await fileSystem.OpenFileAsync("index.bin", FileMode.Create, FileAccess.ReadWrite));

            archiveBw.WriteString("ARC0", Encoding.UTF8, false, false);
            indexBw.WriteString("IDX0", Encoding.UTF8, false, false);

            indexBw.Write(_files.Count);
            archiveBw.Write(new byte[0xC]);

            foreach (var file in _files)
            {
                indexBw.Write((int)archiveBw.BaseStream.Position);
                indexBw.Write((int)file.FileSize);

                file.SaveFileData(archiveBw.BaseStream, null);
            }
        }
Beispiel #30
0
        public static long Rebuild(Stream instream, List <ExeFSFileInfo> files, string root)
        {
            var inOffset = instream.Position;

            List <ExeFS.ExeFSHeader> fileHeaders = new List <ExeFS.ExeFSHeader>();
            var fileOffset = 0;

            foreach (var file in files)
            {
                var size = (file.compressed) ? RevLZ77.Compress(file.FileData).Length : (int)file.FileSize;
                fileHeaders.Add(new ExeFS.ExeFSHeader
                {
                    name   = Path.GetFileName(file.FileName).Replace(root, ""),
                    offset = fileOffset,
                    size   = size
                });
                fileOffset += size;
                fileOffset  = Align(fileOffset);
            }

            List <byte[]> fileHash = new List <byte[]>();

            instream.Seek(ExeFS.exeFSHeaderSize, SeekOrigin.Current);
            foreach (var file in files)
            {
                fileHash.Add(file.Write(instream));
                Align(instream);
            }
            fileHash.Reverse();

            var finalSize = instream.Position - inOffset;

            instream.Position = inOffset;
            using (var bw = new BinaryWriterX(instream, true))
            {
                foreach (var exefsFile in fileHeaders)
                {
                    bw.WriteStruct(exefsFile);
                }
                bw.WritePadding(maxFiles * fileHeaderLength - fileHeaders.Count * fileHeaderLength);

                bw.WritePadding(0x20);

                bw.WritePadding(maxFiles * 0x20 - fileHash.Count * 0x20);
                foreach (var hash in fileHash)
                {
                    bw.Write(hash);
                }
            }

            instream.Position = inOffset + finalSize;
            //instream.Position = bkOffset;

            return(finalSize);
        }
Beispiel #31
0
        public void Save(Stream texInput, Stream texiInput)
        {
            //Check sizes, if mipMaps
            if (bmps.Count > 1)
            {
                var bmpW = bmps[0].Width / 2;
                var bmpH = bmps[0].Height / 2;
                for (int i = 1; i < bmps.Count; i++)
                {
                    if (bmps[i].Width != bmpW)
                    {
                        throw new Exception($"Width of image {i} has to be {bmpW}");
                    }
                    if (bmps[i].Height != bmpH)
                    {
                        throw new Exception($"Width of image {i} has to be {bmpH}");
                    }
                    bmpW /= 2;
                    bmpH /= 2;
                }
            }

            //Creating image
            using (var bw = new BinaryWriterX(texInput))
            {
                var width       = (Integer)seri.Parameters.Find(x => x.Name == "w");
                var height      = (Integer)seri.Parameters.Find(x => x.Name == "h");
                var owidth      = (Integer)seri.Parameters.Find(x => x.Name == "ow");
                var oheight     = (Integer)seri.Parameters.Find(x => x.Name == "oh");
                var mipMapCount = (Integer)seri.Parameters.Find(x => x.Name == "mipmap");
                var format      = (Integer)seri.Parameters.Find(x => x.Name == "format");

                width.Value   = bmps[0].Width;
                height.Value  = bmps[0].Height;
                owidth.Value  = bmps[0].Width;
                oheight.Value = bmps[0].Height;

                foreach (var bmp in bmps)
                {
                    var settings = new ImageSettings
                    {
                        Width   = bmp.Width,
                        Height  = bmp.Height,
                        Format  = Support.Format[format.Value],
                        Swizzle = new CTRSwizzle(bmp.Width, bmp.Height)
                    };

                    bw.Write(Common.Save(bmp, settings));
                }

                XmlSerializer Serializer = new XmlSerializer(typeof(SERIList));
                Serializer.Serialize(texiInput, seri);
                texiInput.Close();
            }
        }