Beispiel #1
0
        public override void SaveTo(Stream Stream, bool DoAlign = true)
        {
            var ListStart = Marshal.SizeOf(typeof(HeaderStruct));
            var DataStart = ListStart + Marshal.SizeOf(typeof(EntryStruct)) * Entries.Count;

            Stream.Position = DataStart;
            Stream.WriteByteRepeated(0x00, 0x10);
            foreach (var Entry in Entries)
            {
                Entry.EntryStruct.Offset = (uint)(Stream.Position - DataStart);
                Stream.WriteStream(Entry.CompressedStream);
                Stream.WriteZeroToAlign(0x10);
            }

            Stream.Position = 0;

            this.Header.Magic     = "TO8SCEL\0";
            this.Header.TotalSize = (uint)Stream.Length;
            this.Header.ListCount = (uint)Entries.Count;
            this.Header.ListStart = (uint)ListStart;
            this.Header.DataStart = (uint)DataStart;
            this.Header.DataEnd   = (uint)Stream.Length;

            Stream.WriteStruct(this.Header);

            foreach (var Entry in Entries)
            {
                Stream.WriteStruct(Entry.EntryStruct);
            }
        }
Beispiel #2
0
 public static void WriteBgra(Stream output, Color color)
 {
     output.WriteStruct(color.B);
     output.WriteStruct(color.G);
     output.WriteStruct(color.R);
     output.WriteStruct(color.A);
 }
Beispiel #3
0
        private void SendUpdate(Stream dst)
        {
            var str = new StringBuilder();

            str.Append("<>");
            str.Append("<type>updBuddyList</type>");
            foreach (var friend in chat.Friends)
            {
                str.Append($"<buddy>{friend.Name}</buddy>");
            }
            str.Append("</>");
            var header  = new MaestroMessageHeader(MaestroMessageType.CHATMESSAGE_TO_GAME, str.Length);
            var payload = str.ToString().GetBytes();

            dst.WriteStruct(header);
            dst.Write(payload);

            str.Clear();
            str.Append("<>");
            str.Append("<type>updIgnoreList</type>");
            str.Append("</>");
            header  = new MaestroMessageHeader(MaestroMessageType.CHATMESSAGE_TO_GAME, str.Length);
            payload = str.ToString().GetBytes();
            dst.WriteStruct(header);
            dst.Write(payload);
        }
Beispiel #4
0
        public void Save(Stream bnkStream, Stream mbnkStream)
        {
            Header.NumFiles   = (uint)Files.Count;
            Header.HeaderSize = (uint)(Marshal.SizeOf(typeof(SoundbankHeader)) + (Marshal.SizeOf(typeof(SoundbankEntryInfo)) * Header.NumFiles));
            bnkStream.WriteStruct(Header);
            mbnkStream.WriteStruct(Header);
            uint nextOffset = Header.HeaderSize;

            nextOffset = nextOffset.Align(0x800);
            foreach (var entry in Files)
            {
                entry.Info.Offset = nextOffset;
                nextOffset       += entry.Info.MetadataLength + entry.Info.AudioLength;
                nextOffset        = nextOffset.Align(0x800);
                bnkStream.WriteStruct(entry.Info);
                mbnkStream.WriteStruct(entry.Info);
            }

            int count = 0;

            foreach (var entry in Files)
            {
                bnkStream.Seek(entry.Info.Offset, SeekOrigin.Begin);
                Stream metadataStream = m_MetadataStreams[count];
                if (metadataStream != null)
                {
                    metadataStream.Seek(0, SeekOrigin.Begin);
                    metadataStream.CopyTo(bnkStream);
                }
                Stream audioStream = m_AudioStreams[count];
                audioStream.CopyTo(bnkStream);
                count++;
            }
        }
Beispiel #5
0
 public override void Serialize(Stream stream, GameStateSerializer serializer)
 {
     stream.WriteStruct(animationCountdown);
     stream.WriteStruct(animationIndex);
     stream.WriteStruct(directionChangeCountdown);
     stream.WriteStruct(currentOrientation);
     stream.WriteStruct(headingOrientation);
     base.Serialize(stream, serializer);
 }
Beispiel #6
0
 public override void Serialize(Stream stream, GameStateSerializer serializer)
 {
     stream.WriteStruct(spawnCooldown);
     stream.WriteStruct(surfingSpawnCooldown);
     stream.WriteFloat(surfingSpawnCooldownNonRounded);
     stream.WriteFloat(penguinDurationBonus);
     stream.WriteFloat(penguinDestroyBonus);
     base.Serialize(stream, serializer);
 }
        public override void Serialize(Stream stream, GameStateSerializer serializer)
        {
            stream.WriteInt(clicks);
            stream.WriteStruct(scoreBonus);
            stream.WriteStruct(activationCounter);
            stream.WriteBool(shouldActivate);

            base.Serialize(stream, serializer);
        }
Beispiel #8
0
 private static void WriteHeader(Stream stream, DDS_HEADER header, DDS_HEADER_DXT10 dxt10header)
 {
     stream.Write(BitConverter.GetBytes(DDS_MAGIC), 0, 4);
     stream.WriteStruct(header);
     if (header.ddspf.dwFourCC == MAKEFOURCC('D', 'X', '1', '0'))
     {
         stream.WriteStruct(dxt10header);
     }
 }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="count"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public BitWriter2 WriteBits(int count, uint value)
        {
            if (count > _leftBits)
            {
                var bits1 = _leftBits;
                var bits2 = count - _leftBits;
                WriteBits(bits1, value >> (count - bits1));
                WriteBits(bits2, value);
                return(this);
            }

            if (LSB)
            {
                _currentValue |= (value & BitUtils.CreateMask(count)) << (CurrentBits);
            }
            else
            {
                _currentValue |= (value & BitUtils.CreateMask(count)) << (_leftBits - count);
            }
            _leftBits -= count;

            if (_leftBits != 0)
            {
                return(this);
            }

            //Console.WriteLine("Writting: {0:X" + (ByteCapacity * 2) + "}", CurrentValue);
            switch (_byteCapacity)
            {
            case 1:
                Stream.WriteByte((byte)_currentValue);
                break;

            case 2:
                Stream.WriteStruct((ushort)_currentValue);
                break;

            case 4:
                // ReSharper disable once RedundantCast
                Stream.WriteStruct((uint)_currentValue);
                break;

            default:
                throw(new InvalidOperationException());
            }
            ResetValue();

            return(this);
        }
        public void Save(Stream stream)
        {
            stream.WriteUInt16((UInt16)Name.Length);
            stream.WriteAsciiString(Name);
            stream.WriteUInt8(ContainerType);
            stream.WriteUInt16((UInt16)Flags);
            stream.WriteUInt16((UInt16)Primitives.Count);
            stream.WriteUInt32(PackfileBaseOffset);
            stream.WriteUInt8(CompressionType);
            if (StubContainerParentName != null && StubContainerParentName != "")
            {
                stream.WriteUInt16((UInt16)StubContainerParentName.Length);
                stream.WriteAsciiString(StubContainerParentName);
            }
            else
            {
                stream.WriteUInt16(0);
            }
            stream.WriteInt32(AuxData.Length);
            stream.Write(AuxData, 0, AuxData.Length);
            stream.WriteInt32(TotalCompressedPackfileReadSize);

            foreach (WriteTimeSizes sizes in PrimitiveSizes)
            {
                stream.WriteStruct(sizes);
            }

            foreach (Primitive primitive in Primitives)
            {
                primitive.Save(stream);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Creates an entry in the archive and writes to int without compression
        /// </summary>
        /// <param name="hash">The path hash to identify the entry</param>
        /// <param name="content">The content of the entry</param>
        /// <param name="length">The uncompresses length of the content, if it is compressed</param>
        /// <param name="compressed">True if the contents is compressed</param>
        public void Write(ulong hash, byte[] content, int length, bool compressed)
        {
            if (!compressed && length != content.Length)
            {
                throw new ArgumentException("Uncompressed data size missmatch");
            }

            lock (_lock) {
                output.Seek(headersOffset, SeekOrigin.Begin);
                output.WriteStruct(new WADArchive.FileInfo {
                    PathHash = hash,
                    Offset   = (uint)contentOffset,
                    ZipSize  = (uint)content.Length,
                    Size     = (uint)length,
                    Zipped   = (uint)(compressed ? 1 : 0),
                    SHA256   = BitConverter.ToUInt64(SHA256.ComputeHash(content), 0)//First 8 bytes of SHA256
                });
                headersOffset = output.Position;

                output.Seek(contentOffset, SeekOrigin.Begin);
                output.Write(content, 0, content.Length);
                contentOffset = output.Position;

                this.count++;
            }
        }
Beispiel #12
0
        public void WriteWave(Stream Stream, StereoShortSoundSample[] Samples)
        {
            this.Stream       = Stream;
            this.BinaryWriter = new BinaryWriter(Stream);

            WriteChunk("RIFF", () =>
            {
                Stream.WriteStringz("WAVE", 4, Encoding.ASCII);
                WriteChunk("fmt ", () =>
                {
                    Stream.WriteStruct(new WaveFormat()
                    {
                        CompressionCode  = 1,
                        SampleRate       = 44100,
                        NumberOfChannels = 2,
                        BytesPerSecond   = 44100 * sizeof(short) * 2,
                        BlockAlignment   = sizeof(short) * 2,
                        BitsPerSample    = 16,
                        Padding          = 0,
                    });
                });
                WriteChunk("data", () =>
                {
                    BinaryWriter.Write(PointerUtils.ArrayToByteArray(Samples));

                    /*
                     * foreach (var Sample in Samples)
                     * {
                     *  BinaryWriter.Write(Sample.Left);
                     *  BinaryWriter.Write(Sample.Right);
                     * }
                     */
                });
            });
        }
Beispiel #13
0
        public void WriteWave(Stream Stream, short[] Samples)
        {
            this.Stream       = Stream;
            this.BinaryWriter = new BinaryWriter(Stream);

            WriteChunk("RIFF", () =>
            {
                Stream.WriteStringz("WAVE", 4, Encoding.ASCII);
                WriteChunk("fmt ", () =>
                {
                    Stream.WriteStruct(new WaveFormat()
                    {
                        CompressionCode  = 1,
                        SampleRate       = 44100,
                        NumberOfChannels = 2,
                        BytesPerSecond   = 44100 * sizeof(short) * 2,
                        BlockAlignment   = sizeof(short) * 2,
                        BitsPerSample    = 16,
                        Padding          = 0,
                    });
                });
                WriteChunk("data", () =>
                {
                    foreach (var Sample in Samples)
                    {
                        BinaryWriter.Write(Sample);
                    }
                });
            });
        }
Beispiel #14
0
        public void Save(Stream stream)
        {
            stream.WriteUInt16((UInt16)Name.Length);
            stream.WriteAsciiString(Name);
            stream.WriteUInt8(ContainerType);
            stream.WriteUInt16((UInt16)Flags);
            stream.WriteUInt16((UInt16)Primitives.Count);
            stream.WriteUInt32(PackfileBaseOffset);
            stream.WriteUInt8(CompressionType);
            if (StubContainerParentName != null && StubContainerParentName != "")
            {
                stream.WriteUInt16((UInt16)StubContainerParentName.Length);
                stream.WriteAsciiString(StubContainerParentName);
            }
            else
            {
                stream.WriteUInt16(0);
            }
            stream.WriteInt32(AuxData.Length);
            stream.Write(AuxData, 0, AuxData.Length);
            stream.WriteInt32(TotalCompressedPackfileReadSize);

            foreach (WriteTimeSizes sizes in PrimitiveSizes)
            {
                stream.WriteStruct(sizes);
            }

            foreach (Primitive primitive in Primitives)
            {
                primitive.Save(stream);
            }
        }
        public void HandlePacketTest()
        {
            var TestPacketHelperInstance = new TestPacketHelper(
                Packet.PacketType.ListElements,
                new ListElementsHandler()
                );

            var Ranking = TestPacketHelperInstance.DescendingIndex;

            Ranking.UpdateUserScore(1000, 10000, 250);
            Ranking.UpdateUserScore(1001, 10000, 200);
            Ranking.UpdateUserScore(1002, 10000, 150);
            Ranking.UpdateUserScore(1003, 10000, 100);
            Ranking.UpdateUserScore(1004, 10000, 50);

            TestPacketHelperInstance.Handle((Stream) => {
                Stream.WriteStruct(new ListElementsHandler.RequestStruct()
                {
                    RankingIndexId = TestPacketHelperInstance.DescendingIndex.IndexId,
                    Offset         = 2,
                    Count          = 2,
                });
            });

            Assert.AreEqual(
                "ResponseEntryStruct(Position=2,UserId=1002,ScoreValue=150,ScoreTimeStamp=10000)" +
                "ResponseEntryStruct(Position=3,UserId=1003,ScoreValue=100,ScoreTimeStamp=10000)" +
                "",
                TestPacketHelperInstance.PacketToSend.Stream.ReadStructVectorUntilTheEndOfStream <ListElementsHandler.ResponseEntryStruct>().ToStringArray("")
                );
        }
Beispiel #16
0
 public static void WriteStructVector <T>(this Stream Stream, T[] Vector) where T : struct
 {
     for (int n = 0; n < Vector.Length; n++)
     {
         Stream.WriteStruct(Vector[n]);
     }
 }
Beispiel #17
0
        public void HandlePacketTest()
        {
            var TestPacketHelperInstance = new TestPacketHelper(
                Packet.PacketType.RemoveAllElements,
                new RemoveAllElementsHandler()
                );

            var Index = TestPacketHelperInstance.DescendingIndex;

            Index.UpdateUserScore(1000, 10000, 300);
            Index.UpdateUserScore(1001, 10000, 250);
            Index.UpdateUserScore(1002, 10000, 200);

            TestPacketHelperInstance.Handle((Stream) =>
            {
                Stream.WriteStruct(new RemoveAllElementsHandler.RequestStruct()
                {
                    RankingIndexId = Index.IndexId,
                });
            });

            Assert.AreEqual(
                "",
                Index.GetRange(0, 10000).ToStringArray("\r\n")
                );
        }
        public void Save(Stream bnkStream, Stream mbnkStream)
        {
            Header.NumFiles = (uint)Files.Count;
            Header.HeaderSize = (uint)(Marshal.SizeOf(typeof(SoundbankHeader)) + (Marshal.SizeOf(typeof(SoundbankEntryInfo)) * Header.NumFiles));
            bnkStream.WriteStruct(Header);
            mbnkStream.WriteStruct(Header);
            uint nextOffset = Header.HeaderSize;
            nextOffset = nextOffset.Align(0x800);
            foreach (var entry in Files)
            {
                entry.Info.Offset = nextOffset;
                nextOffset += entry.Info.MetadataLength + entry.Info.AudioLength;
                nextOffset = nextOffset.Align(0x800);
                bnkStream.WriteStruct(entry.Info);
                mbnkStream.WriteStruct(entry.Info);
            }

            int count = 0;
            foreach (var entry in Files)
            {
                bnkStream.Seek(entry.Info.Offset, SeekOrigin.Begin);
                Stream metadataStream = m_MetadataStreams[count];
                if (metadataStream != null)
                {
                    metadataStream.Seek(0, SeekOrigin.Begin);
                    metadataStream.CopyTo(bnkStream);
                }
                Stream audioStream = m_AudioStreams[count];
                audioStream.CopyTo(bnkStream);
                count++;
            }

        }
Beispiel #19
0
        public void WriteWave(Stream Stream, StereoShortSoundSample[] Samples)
        {
            this.Stream = Stream;
            this.BinaryWriter = new BinaryWriter(Stream);

            WriteChunk("RIFF", () =>
            {
                Stream.WriteStringz("WAVE", 4, Encoding.ASCII);
                WriteChunk("fmt ", () =>
                {
                    Stream.WriteStruct(new WaveFormat()
                    {
                        CompressionCode = 1,
                        SampleRate = 44100,
                        NumberOfChannels = 2,
                        BytesPerSecond = 44100 * sizeof(short) * 2,
                        BlockAlignment = sizeof(short) * 2,
                        BitsPerSample = 16,
                        Padding = 0,
                    });
                });
                WriteChunk("data", () =>
                {
                    BinaryWriter.Write(PointerUtils.ArrayToByteArray(Samples));
                    /*
                    foreach (var Sample in Samples)
                    {
                        BinaryWriter.Write(Sample.Left);
                        BinaryWriter.Write(Sample.Right);
                    }
                    */
                });
            });
        }
Beispiel #20
0
        public void WriteWave(Stream Stream, short[] Samples)
        {
            this.Stream = Stream;
            this.BinaryWriter = new BinaryWriter(Stream);

            WriteChunk("RIFF", () =>
            {
                Stream.WriteStringz("WAVE", 4, Encoding.ASCII);
                WriteChunk("fmt ", () =>
                {
                    Stream.WriteStruct(new WaveFormat()
                    {
                        CompressionCode = 1,
                        SampleRate = 44100,
                        NumberOfChannels = 2,
                        BytesPerSecond = 44100 * sizeof(short) * 2,
                        BlockAlignment = sizeof(short) * 2,
                        BitsPerSample = 16,
                        Padding = 0,
                    });
                });
                WriteChunk("data", () =>
                {
                    foreach (var Sample in Samples) BinaryWriter.Write(Sample);
                });
            });
        }
Beispiel #21
0
 public static void WriteEntry(Stream stream, TarHeader header, Stream data)
 {
     header.Checksum = header.ComputeChecksum();
     stream.WriteStruct(header);
     Align(stream);
     data.CopyTo(stream);
     Align(stream);
 }
Beispiel #22
0
        static public void CreateCompression15File(String FileName, Stream OutputStream, int FallbackCompression = 15)
        {
            /*
             * if (pState->block_type == LZX_BLOCKTYPE_UNCOMPRESSED)
             * {
             *      if (pState->block_length & 1) inpos++; // realign bitstream to word
             *      INIT_BITSTREAM;
             * }
             */

            //throw (new NotImplementedException("Can't compress using LZX. Please use compressión 03 instead."));
            Stream LZXStream;

            try
            {
                LZXStream = CompressToLZXStream(FileName, FallbackCompression);
            }
            catch (InvalidDataException)
            {
                if (FallbackCompression == 15)
                {
                    LZXStream = CompressToLZXStreamRAW(FileName);
                }
                else
                {
                    OutputStream.WriteBytes(TalesCompression.CreateFromVersion(FallbackCompression).EncodeBytes(File.ReadAllBytes(FileName)));
                    return;
                }
            }

            uint UncompressedSize = (uint)(new FileInfo(FileName)).Length;
            uint CompressedSize   = (uint)LZXStream.Length;
            var  HeaderStruct     = new TalesCompression15_Lzx.HeaderStruct()
            {
                Magic               = TalesCompression15_Lzx.Signature,
                Magic1              = 0x20000,
                Magic2              = 0x80000,
                Magic3              = 0x00000,
                Magic4              = 0x00000,
                UncompressedSize    = UncompressedSize,
                UncompressedSize2   = UncompressedSize,
                CompressedSize      = CompressedSize,
                CompressedSize2     = CompressedSize,
                CompressedSizePlus4 = CompressedSize + 4,
            };

            OutputStream.WriteStruct(HeaderStruct);
            LZXStream.CopyTo(OutputStream);
            OutputStream.Flush();

            //Console.WriteLine(OutputStream.Position);
            //Console.WriteLine(0x34 + CompressedSize);

            if (OutputStream.Position != 0x34 + CompressedSize)
            {
                throw (new Exception("(OutputStream.Position != 0x34 + CompressedSize)"));
            }
        }
Beispiel #23
0
        override public void SaveTo(Stream Stream, bool DoAlign = true)
        {
            var SpaceAssigner1D = new SpaceAssigner1D().AddAllPositiveAvailable();
            var SpaceAssigner1DUniqueAllocator = new SpaceAssigner1DUniqueAllocatorStream(SpaceAssigner1D, new MemoryStream());

            SpaceAssigner1DUniqueAllocator.Encoding = Encoding.UTF8;

            SpaceAssigner1DUniqueAllocator.AllocateUnique(SpaceAssigner1DUniqueAllocator.Encoding.GetBytes("dummy"));
            SpaceAssigner1DUniqueAllocator.AllocateUnique(new byte[] { 0 });

            var EntryStructs = new List <EntryStruct>();

            foreach (var Entry in Entries)
            {
                EntryStructs.Add(new EntryStruct()
                {
                    OffsetTitle          = (uint)SpaceAssigner1DUniqueAllocator.AllocateUnique(Entry.Title).Min,
                    OffsetTextOriginal   = (uint)SpaceAssigner1DUniqueAllocator.AllocateUnique(Entry.TextOriginal).Min,
                    OffsetTextTranslated = (uint)SpaceAssigner1DUniqueAllocator.AllocateUnique(Entry.TextTranslated).Min,
                    Talker = (uint)Entry.Talker,
                });
            }

            var OffsetEntries = Marshal.SizeOf(typeof(HeaderStruct));
            var OffsetTexts   = OffsetEntries + Entries.Count * Marshal.SizeOf(typeof(EntryStruct));
            var OffsetEnd     = OffsetTexts + SpaceAssigner1DUniqueAllocator.Stream.Length;

            Stream.WriteStruct(new HeaderStruct()
            {
                Magic         = "TO8CHTX",
                OffsetEntries = (uint)OffsetEntries,
                OffsetTexts   = (uint)OffsetTexts,
                TextCount     = (uint)Entries.Count,
                FileSize      = (uint)OffsetEnd,
                Padding       = 0,
            });


            foreach (var EntryStruct in EntryStructs)
            {
                Stream.WriteStruct(EntryStruct);
            }

            SpaceAssigner1DUniqueAllocator.Stream.CopyToFast(Stream);
        }
 public static void WriteEntry(Stream output, ArHeader header, Stream data)
 {
     output.WriteStruct(header);
     data.CopyTo(output);
     if (output.Position % 2 != 0)
     {
         output.WriteByte(0);
     }
 }
Beispiel #25
0
        private void getWaveStream(Stream stream, int idx)
        {
            AudioFile audioFile = audioList[idx];

            stream.WriteStruct <RiffChunk>(audioFile.riffChunk);
            stream.WriteStruct <FormatChunk>(audioFile.formatChunk);
            stream.WriteStruct <DataChunk>(audioFile.dataChunk);

            if (audioFile.Data != null)
            {
                stream.Write(audioFile.Data, 0, audioFile.Data.Length);
            }

            if (audioFile.fmtHeader.Loop > 0)
            {
                stream.WriteStruct <LoopChunk>(audioFile.loopChunk);
            }
        }
Beispiel #26
0
        public void Save(Stream s)
        {
            s.WriteStruct(Header);

            foreach (SimulatedNodeInfo sni in Nodes)
            {
                s.WriteStruct(sni);
            }

            foreach (SimulatedNodeLinkInfo snli in NodeLinks)
            {
                s.WriteStruct(snli);
            }

            foreach (ClothSimCollisionPrimitiveInfo cscpi in CollisionPrimitives)
            {
                s.WriteStruct(cscpi);
            }

            s.Align(8);

            foreach (ClothSimRopeInfo csri in Ropes)
            {
                s.WriteStruct(csri);
            }

            for (int i = 0; i < Header.NumRopes; i++)
            {
                List <UInt32> ropeNodes = RopeNodes[i];

                foreach (UInt32 ropeNode in ropeNodes)
                {
                    s.WriteUInt32(ropeNode);
                }

                List <UInt32> ropeLinks = RopeLinks[i];

                foreach (UInt32 ropeLink in ropeLinks)
                {
                    s.WriteUInt32(ropeLink);
                }
            }
        }
Beispiel #27
0
        private void WriteIndexedImage(GLTexture texture, GLTexture palette)
        {
            byte[]    palettesPixels = palette.GetManagedPixelsArray(PixelFormat.Format32bppArgb);
            TexHeader header         = CreateHeader(texture, palette, palettesPixels[3] == 0);

            _output.WriteStruct(header);
            _output.Write(palettesPixels, 0, palettesPixels.Length);
            using (SafeHGlobalHandle pixels = texture.GetUnmanagedPixelsArray(PixelFormat.Format8bppIndexed))
                using (UnmanagedMemoryStream input = pixels.OpenStream(FileAccess.Read))
                    input.CopyTo(_output);
        }
Beispiel #28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="InputStream"></param>
        /// <param name="OutputStream"></param>
        public override void EncodeFile(Stream InputStream, Stream OutputStream)
        {
            var Header = new TalesCompression1_3.HeaderStruct()
            {
                Version            = 0,
                CompressedLength   = (uint)InputStream.Length,
                UncompressedLength = (uint)OutputStream.Length,
            };

            OutputStream.WriteStruct(Header);
            InputStream.CopyToFast(OutputStream);
        }
Beispiel #29
0
        public WADBuilder(string file, int count, byte[] unk, ulong unk2)
        {
            this.output = File.Create(file);

            output.WriteStruct(new WADArchive.Header {
                Magic = Magic,
                Major = Major,
                Minor = Minor
            });

            output.Write(unk, 0, unk.Length);

            headersOffset = output.Position + 16;

            output.WriteStruct(unk2);
            output.WriteStruct((ushort)headersOffset);
            output.WriteStruct((ushort)Marshal.SizeOf <WADArchive.FileInfo>());
            output.WriteStruct(count);

            contentOffset = headersOffset + count * Marshal.SizeOf <WADArchive.FileInfo>();
        }
Beispiel #30
0
        public void write(Stream stream)
        {
            int writeIndex = 0;

            writeIndex += stream.WriteStruct(fileHeader);

            writeIndex += stream.WriteStruct(infoHeader);

            byte[] paddingBuffer = new byte[padding];

            // Avoid accessing the size properties too much
            uint _height = uheight;
            uint _width  = width;
            uint _size   = _height * _width;

            // Optimize loop if there is no adding
            if (paddingBuffer.Length > 0)
            {
                uint index = 0;
                for (uint i = 0; i < _height; i++)
                {
                    for (uint j = 0; j < _width; j++, index++)
                    {
                        BGR color = this[j, i];
                        writeIndex += stream.WriteStruct(color);
                    }

                    stream.Write(paddingBuffer, 0, paddingBuffer.Length);
                }
            }
            else
            {
                for (uint i = 0; i < _size; i++)
                {
                    BGR color = this[i];
                    writeIndex += stream.WriteStruct(color);
                }
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="index"></param>
 public TType this[int index]
 {
     get
     {
         SeekToIndex(index);
         return(Stream.ReadStruct <TType>());
     }
     set
     {
         SeekToIndex(index);
         Stream.WriteStruct(value);
     }
 }
Beispiel #32
0
        public void write(Stream stream)
        {
            int writeIndex = 0;

            writeIndex += stream.WriteStruct(fileHeader);

            writeIndex += stream.WriteStruct(infoHeader);

            byte[] paddingBuffer = new byte[padding];

            // Avoid accessing the size properties too much
            uint _height = uheight;
            uint _width = width;
            uint _size = _height * _width;

            // Optimize loop if there is no adding
            if (paddingBuffer.Length > 0)
            {
                uint index = 0;
                for (uint i = 0; i < _height; i++)
                {
                    for (uint j = 0; j < _width; j++, index++)
                    {
                        BGR color = this[j, i];
                        writeIndex += stream.WriteStruct(color);
                    }

                    stream.Write(paddingBuffer, 0, paddingBuffer.Length);
                }
            }
            else
            {
                for (uint i = 0; i < _size; i++)
                {
                    BGR color = this[i];
                    writeIndex += stream.WriteStruct(color);
                }
            }
        }
        public BitWriter2 WriteBits(int Count, uint Value)
        {
            if (Count > LeftBits)
            {
                int Bits1 = LeftBits;
                int Bits2 = Count - LeftBits;
                WriteBits(Bits1, Value >> (Count - Bits1));
                WriteBits(Bits2, Value);
                return(this);
            }

            if (LSB)
            {
                CurrentValue |= (uint)((Value & BitUtils.CreateMask(Count)) << (CurrentBits));
            }
            else
            {
                CurrentValue |= (uint)((Value & BitUtils.CreateMask(Count)) << (LeftBits - Count));
            }
            LeftBits -= Count;

            if (LeftBits == 0)
            {
                //Console.WriteLine("Writting: {0:X" + (ByteCapacity * 2) + "}", CurrentValue);
                switch (ByteCapacity)
                {
                case 1: Stream.WriteByte((byte)CurrentValue); break;

                case 2: Stream.WriteStruct((ushort)CurrentValue); break;

                case 4: Stream.WriteStruct((uint)CurrentValue); break;
                    throw(new InvalidOperationException());
                }
                ResetValue();
            }

            return(this);
        }
Beispiel #34
0
        public void Save(Stream s)
        {
            using (MemoryStream dirBlockStream = new MemoryStream())
            {
                foreach (PegEntry entry in Entries)
                {
                    dirBlockStream.WriteAsciiNullTerminatedString(entry.Filename);
                }

                // Header size + entry size + string size
                Header.DirBlockSize = (int)(0x18 + (0x48 * Entries.Count) + dirBlockStream.Length);

                s.WriteStruct(Header);

                foreach (PegEntry entry in Entries)
                {
                    s.WriteStruct(entry.Data);
                }

                dirBlockStream.Seek(0, SeekOrigin.Begin);
                dirBlockStream.CopyTo(s);
            }
        }
Beispiel #35
0
        public void SaveTo(Stream Stream)
        {
            long OutStart = Stream.Position;

            Header.TextLen = (uint)TextStream.Length;

            Stream.WriteStruct(Header);

            Stream.WriteByteRepeatedTo((byte)0x00, OutStart + Header.CodeStart);
            Stream.WriteStream(CodeStream.Slice());

            Stream.WriteByteRepeatedTo((byte)0x00, OutStart + Header.TextStart);
            Stream.WriteStream(TextStream.Slice());
        }
 public void Save(Stream s)
 {
     byte[] sectionData = null;
     using (MemoryStream ms = new MemoryStream())
     {
         foreach (Section section in Sections.Values)
         {
             section.Save(ms);
         }
         sectionData = ms.ToArray();
     }
     MainHeader.Checksum = Hashes.CrcVolition(sectionData);
     s.WriteStruct(MainHeader);
     s.Write(sectionData, 0, sectionData.Length);
 }
        public void Save(Stream stream)
        {
            Header.NumContainers = (short)Containers.Count;

            stream.WriteStruct(Header);

            // Write allocator types
            stream.WriteUInt32((uint)AllocatorTypes.Count);
            foreach (var pair in AllocatorTypes)
            {
                byte id = pair.Key;
                string name = pair.Value;
                stream.WriteUInt16((UInt16)name.Length);
                stream.WriteAsciiString(name);
                stream.WriteUInt8(id);
            }

            // Write primitive types
            stream.WriteUInt32((uint)PrimitiveTypes.Count);
            foreach (var pair in PrimitiveTypes)
            {
                byte id = pair.Key;
                string name = pair.Value;
                stream.WriteUInt16((UInt16)name.Length);
                stream.WriteAsciiString(name);
                stream.WriteUInt8(id);
            }

            // Write container types
            stream.WriteUInt32((uint)ContainerTypes.Count);
            foreach (var pair in ContainerTypes)
            {
                byte id = pair.Key;
                string name = pair.Value;
                stream.WriteUInt16((UInt16)name.Length);
                stream.WriteAsciiString(name);
                stream.WriteUInt8(id);
            }

            // Write containers
            foreach (Container container in Containers)
            {
                container.Save(stream);
            }
        }
        public void Save(Stream stream)
        {
            // Calculate IndexSize
            FileData.IndexCount = (uint)Files.Count;
            FileData.IndexSize = (FileData.IndexCount * 0x1C);

            // Write Names & calculate NamesSize
            Dictionary<string, uint> filenames = new Dictionary<string, uint>(StringComparer.InvariantCultureIgnoreCase);
            stream.Seek(CalculateEntryNamesOffset(), SeekOrigin.Begin);
            uint filenameOffset = 0;
            foreach (PackfileEntry entry in Files)
            {
                string filename = Path.GetFileNameWithoutExtension(entry.Name);

                if (filenames.ContainsKey(filename))
                {
                    entry.Data.FilenameOffset = filenames[filename];
                }
                else
                {
                    entry.Data.FilenameOffset = filenameOffset;
                    int length = stream.WriteAsciiNullTerminatedString(filename);
                    filenames.Add(filename, filenameOffset);
                    filenameOffset += (uint)length;
                }

            }
            FileData.NamesSize = filenameOffset;
            
            // Write Extensions & calculate ExtensionsSize
            Dictionary<string, uint> extensions = new Dictionary<string, uint>(StringComparer.InvariantCultureIgnoreCase);
            uint extensionOffset = 0;
            stream.Seek(CalculateExtensionsOffset(), SeekOrigin.Begin);
            foreach (PackfileEntry entry in Files)
            {
                string extension = Path.GetExtension(entry.Name);
                if (extension.StartsWith("."))
                    extension = extension.Remove(0, 1);

                if (extensions.ContainsKey(extension))
                {
                    entry.Data.ExtensionOffset = extensions[extension];
                }
                else
                {
                    entry.Data.ExtensionOffset = extensionOffset;
                    int length = stream.WriteAsciiNullTerminatedString(extension);
                    extensions.Add(extension, extensionOffset);
                    extensionOffset += (uint)length;
                }
            }
            FileData.ExtensionsSize = extensionOffset;

            // Write data
            uint dataOffset = 0;
            stream.Seek(CalculateDataStartOffset(), SeekOrigin.Begin);
            foreach (PackfileEntry entry in Files)
            {
                Stream inStream = m_Streams[entry.Name];
                entry.Data.Size = (uint)inStream.Length;
                entry.Data.Start = dataOffset;
                entry.Data.CompressedSize = (uint)0xFFFFFFFF;
                inStream.CopyTo(stream);
                dataOffset += entry.Data.Size;
                stream.Align(16);
                dataOffset = dataOffset.Align(16);
            }

            // Write Header
            stream.Seek(0, SeekOrigin.Begin);
            FileData.Descriptor = 0x51890ACE;
            FileData.Version = 0x04;
            FileData.CompressedDataSize = 0xFFFFFFFF;
            FileData.UncompressedDataSize = dataOffset;
            FileData.PackageSize = (uint)stream.Length;
            stream.WriteStruct(FileData);
            
            // Write file index
            stream.Seek(GetEntryDataOffset(), SeekOrigin.Begin);
            foreach (PackfileEntry entry in Files)
            {
                stream.WriteStruct(entry.Data);
            }
        }
        public void Save(Stream stream)
        {
            Header.Signature = 0x56414d44;
            Header.LipsyncOffset = 0;
            if (LipsyncData != null)
            {
                Header.LipsyncSize = (uint)LipsyncData.Length;
                stream.Seek(0x24, SeekOrigin.Begin);
                stream.Write(LipsyncData, 0, LipsyncData.Length);
            }
            else
                Header.LipsyncSize = 0;
            
            Header.SubtitleOffset = Header.LipsyncSize;

            uint startOfSubtitles = 0x24 + Header.LipsyncSize + 0x74;

            uint nextSubtitleOffset = 0;

            if (Subtitles.Count != 0)
            {
                SubtitleHeader = new AudioMetadataSubtitleHeader();
                SubtitleHeader.Version = 3;
                SubtitleHeader.LocalizedVoiceSubtitleHeaders = new LocalizedVoiceSubtitleHeader[14];
                for (int i = 0; i < SubtitleHeader.LocalizedVoiceSubtitleHeaders.Length; i++)
                {
                    Language language = (Language)i;

                    string subtitle = Subtitles[language];
                    if (subtitle == "")
                    {
                        SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Offset = nextSubtitleOffset;
                        SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Length = 0;
                    }
                    else
                    {
                        var map = LanguageUtility.GetEncodeCharMap(Instance, language);

                        byte[] subtitleData;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            for (int pos = 0; pos < subtitle.Length; pos++)
                            {
                                char src = subtitle[pos];
                                char value = src;
                                if (map.ContainsKey(src))
                                    value = map[src];

                                byte[] data = BitConverter.GetBytes(value);
                                ms.Write(data, 0, data.Length);
                            }
                            ms.WriteUInt16(0);
                            subtitleData = ms.ToArray();
                        }
                        SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Offset = nextSubtitleOffset;
                        SubtitleHeader.LocalizedVoiceSubtitleHeaders[i].Length = (uint)subtitleData.Length;
                        stream.Seek(startOfSubtitles + nextSubtitleOffset, SeekOrigin.Begin);
                        stream.Write(subtitleData, 0, subtitleData.Length);

                        nextSubtitleOffset += (uint)subtitleData.Length;
                    }
                }
                Header.SubtitleSize = nextSubtitleOffset + 0x74;
                stream.Seek(0x24 + Header.SubtitleOffset, SeekOrigin.Begin);
                stream.WriteStruct(SubtitleHeader);
            }
            else
            {
                Header.SubtitleSize = 0;
            }
            stream.Seek(0, SeekOrigin.Begin);
            stream.WriteStruct(Header);
        }
Beispiel #40
0
        public static void Save(Image image, Stream stream)
        {
            if (image == null)
            throw new ArgumentNullException("image");
              if (stream == null)
            throw new ArgumentNullException("stream");

              var convFlags = ConversionFlags.None;
              var header = EncodeTgaHeader(image, ref convFlags);

              // Write header.
              stream.WriteStruct(header);

              // Determine memory required for image data.
              int rowPitch = (convFlags & ConversionFlags.Format888) != 0 ? image.Width * 3 : image.RowPitch;

              // Write pixels.
              using (var sourceStream = new MemoryStream(image.Data, false))
              using (var reader = new BinaryReader(sourceStream))
            #if NET45
              using (var writer = new BinaryWriter(stream, Encoding.Default, true))
            #else
              using (var writer = new BinaryWriter(stream, Encoding.Default))   // Warning: Closes the stream!
            #endif
              {
            for (int y = 0; y < image.Height; y++)
            {
              if ((convFlags & ConversionFlags.Format888) != 0)
              {
            Copy24BppScanline(reader, image.RowPitch, writer);
              }
              else if ((convFlags & ConversionFlags.Swizzle) != 0)
              {
            TextureHelper.SwizzleScanline(reader, image.RowPitch, writer, rowPitch, image.Format, ScanlineFlags.None);
              }
              else
              {
            TextureHelper.CopyScanline(reader, image.RowPitch, writer, rowPitch, image.Format, ScanlineFlags.None);
              }
            }
              }
        }
		public override void Save(Stream gifstream)
		{
			gifstream.WriteByte((byte)GifFlags.ImageSeparator);
			gifstream.WriteStruct(Header);
			if (LocalColorTableFlag)
			{
				for (var i = 0; i < LocalColorMap.Length; i++)
				{
					var entry = (Color24)LocalColorMap[i];
					gifstream.WriteStruct(entry);
				}
			}
			var enc = new GifLZWEncoder(8);
			var encbytes = enc.Compress(Frame.Bitmap8ToPixels());
			gifstream.WriteByte(8);
			var blocks = GifBitmap.MakeSubBlocks(encbytes);
			gifstream.Write(blocks, 0, blocks.Length);
		}
Beispiel #42
0
        public void write(Stream stream)
        {
            int writeIndex = 0;

            // Add the file signature
            writeIndex += stream.WriteStruct(new DDS_Magic() { dwMagic = Magic });

            writeIndex += stream.WriteStruct(ddsHeader);

            // Only write the ddsHeaderDXT10 when the FOURCC.DX10 is set
            if (ddsHeader.ddspf.dwFourCC == DDS_PIXELFORMAT.FOURCC.DX10)
            {
                writeIndex += stream.WriteStruct(ddsHeaderDXT10);
            }

            foreach (var block in blocks)
            {
                DDS_DXT1Block structBlock = block;
                stream.WriteStruct(structBlock);
            }
        }
 public void Save(Stream s)
 {
     s.WriteStruct<SaveGameSectionHeader>(Header);
     s.Write(Data, 0, Data.Length);
 }
        public void Save(Stream stream)
        {
            long dataStart = CalculateDataStartOffset();

            stream.Seek(dataStart, SeekOrigin.Begin);

            long fileStart = 0;

            long compressedSize = 0;
            long uncompressedSize = 0;

            // Output file data
            ZlibStream dataStream = null;
            if (IsCompressed && IsCondensed)
            {
                dataStream = new ZlibStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression, true);
                dataStream.FlushMode = FlushType.Sync;
            }

            long compressedStart = 0;

            for (int i = 0; i < Files.Count; i++)
            {
                IPackfileEntry entry = Files[i];
                Stream fs = m_Streams[entry.Name];

                bool isLast = (i == (Files.Count - 1));

                PackfileEntry pfE = (PackfileEntry)entry;
                var data = pfE.Data;
                data.Start = (uint)fileStart;
                data.Size = (uint)fs.Length;
                data.Alignment = (IsCondensed) ? (ushort)16 : (ushort)1;
                
                if (this.IsCompressed)
                    data.Flags = PackfileEntryFlags.Compressed;

                if (IsCompressed && IsCondensed)
                {
                    fs.CopyTo(dataStream);
                    dataStream.Flush();
                    long afterData = dataStream.TotalOut;
                    data.CompressedSize = (uint)(afterData - compressedStart);
                    compressedStart = afterData;

                    if (IsStr2)
                    {
                        fileStart += data.Size.Align(16);
                        uncompressedSize += data.Size.Align(16);
                        compressedSize += data.CompressedSize;
                    }
                    else
                    {
                        fileStart += data.Size; //.Align(16);
                        if (!isLast)
                        {
                            uncompressedSize += data.Size; //.Align(16);
                            //uint toSkip = data.Size.Align(16) - data.Size;
//                            for (int j = 0; j < toSkip; j++)
                                //dataStream.WriteByte(0);
                        }
                        else
                        {
                            uncompressedSize += data.Size;
                        }
                        compressedSize += data.CompressedSize;
                    }
                }
                else if (IsCondensed)
                {
                    fs.CopyTo(stream);
                    data.CompressedSize = 0xFFFFFFFF;

                    fileStart += data.Size.Align(16);

                    if (isLast)
                        uncompressedSize += data.Size;
                    else
                    {
                        uint toSkip = data.Size.Align(16) - data.Size;
                        uncompressedSize += data.Size.Align(16);
                        stream.Seek(toSkip, SeekOrigin.Current);
                    }

                }
                else if (IsCompressed)
                {
                    long beforeData = stream.Position;
                    using (dataStream = new ZlibStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression, true))
                    {
                        dataStream.FlushMode = FlushType.Sync;
                        fs.CopyTo(dataStream);
                        dataStream.Flush();
                    }
                    long afterData = stream.Position;
                    data.CompressedSize = (uint)(afterData - beforeData);
                    fileStart += data.CompressedSize;
                    uncompressedSize += data.Size;
                    compressedSize += data.CompressedSize;
                }
                else
                {
                    fs.CopyTo(stream);
                    data.CompressedSize = 0xFFFFFFFF;
                    fileStart += data.Size;
                    uncompressedSize += data.Size;
                }

                fs.Close();

                pfE.Data = data;
            }

            if (IsCompressed && IsCondensed)
            {
                dataStream.Close();
            }

            // Output file names
            stream.Seek(CalculateEntryNamesOffset(), SeekOrigin.Begin);
            long startOffset = CalculateEntryNamesOffset();
            foreach (IPackfileEntry entry in Files)
            {
                PackfileEntry pfE = (PackfileEntry)entry;
                stream.Align(2);
                pfE.Data.FilenameOffset = (UInt32)(stream.Position - startOffset);
                stream.WriteAsciiNullTerminatedString(entry.Name);
                stream.Seek(1, SeekOrigin.Current);
                stream.Align(2);
            }
            long nameSize = stream.Position - CalculateEntryNamesOffset();

            // Output file info
            stream.Seek(GetEntryDataOffset(), SeekOrigin.Begin);
            foreach (IPackfileEntry entry in Files)
            {
                PackfileEntry pfE = (PackfileEntry)entry;
                stream.WriteStruct(pfE.Data);
            }
            long dirSize = stream.Position - GetEntryDataOffset();

            // Output header
            stream.Seek(0, SeekOrigin.Begin);
            FileData.Descriptor = 0x51890ACE;
            FileData.Version = 0x0A;
            FileData.HeaderChecksum = 0;
            FileData.FileSize = (uint)stream.Length;
            FileData.NumFiles = (uint)Files.Count;
            FileData.DirSize = (uint)dirSize;
            FileData.FilenameSize = (uint)nameSize;
            FileData.DataSize = (uint)uncompressedSize;
            if (IsCompressed)
                FileData.CompressedDataSize = (uint)compressedSize;
            else
                FileData.CompressedDataSize = 0xFFFFFFFF;
            stream.WriteStruct(FileData);

            uint checksum = 0;
            byte[] checksumBuffer = new byte[0x1C];

            stream.Seek(0x0C, SeekOrigin.Begin);
            stream.Read(checksumBuffer, 0, checksumBuffer.Length);
            checksum = Hashes.CrcVolition(checksumBuffer);

            stream.Seek(0x08, SeekOrigin.Begin);
            stream.WriteUInt32(checksum);

            stream.Flush();
        }