Exemplo n.º 1
0
        public byte[] Export(string[] Content)
        {
            var NewHeader = new HeaderFooter();

            Tools.CopyStruct(Header, ref NewHeader);

            using (MemoryStream OriScript = new MemoryStream(Script))
                using (MemoryStream Stream = new MemoryStream())
                    using (StructWriter Writer = new StructWriter(Stream, Header.Endian == 'B', Encoding)) {
                        NewHeader.StructOffset = 0;

                        OriScript.Position = Header.StructOffset;
                        byte[] StructData = new byte[Align(Header.StructCount * Header.StructSize)];
                        OriScript.Read(StructData, 0, StructData.Length);


                        NewHeader.TypesOffset = (uint)StructData.Length;

                        OriScript.Position = Header.TypesOffset;
                        byte[] TypeData = new byte[Align(Header.TypesCount * Tools.GetStructLength(new TypeDescriptor()))];
                        OriScript.Read(TypeData, 0, TypeData.Length);

                        NewHeader.StringOffset = (uint)(NewHeader.TypesOffset + TypeData.Length);

                        byte[] StrData;
                        using (MemoryStream StrStream = new MemoryStream())
                            using (StructWriter StrWriter = new StructWriter(StrStream, Writer.BigEndian, Encoding)) {
                                Dictionary <string, uint> OffsetMap = new Dictionary <string, uint>();
                                for (int i = 0; i < Content.Length; i++)
                                {
                                    if (OffsetMap.ContainsKey(Content[i]))
                                    {
                                        var Offset = OffsetMap[Content[i]];
                                        BitConverter.GetBytes(Offset).CopyTo(StructData, OffsetPos[i]);
                                    }
                                    else
                                    {
                                        BitConverter.GetBytes((uint)StrWriter.Position).CopyTo(StructData, OffsetPos[i]);
                                        OffsetMap[Content[i]] = (uint)StrWriter.Position;
                                        StrWriter.Write(Content[i], StringStyle.CString);
                                    }
                                }

                                StrWriter.Flush();

                                StrData = new byte[Align(StrStream.Length)];
                                StrStream.ToArray().CopyTo(StrData, 0);
                            }


                        Writer.Write(StructData);
                        Writer.Write(TypeData);
                        Writer.Write(StrData);
                        Writer.WriteStruct(ref NewHeader);
                        Writer.Flush();

                        return(Stream.ToArray());
                    }
        }
Exemplo n.º 2
0
        private void WriteString(StructWriter Stream, string Content)
        {
            byte[] Buffer = Encoding.UTF8.GetBytes(Content);
            WriteNum(Stream, Buffer.LongLength);

            Stream.Write(Buffer, 0, Buffer.Length);
        }
Exemplo n.º 3
0
        public static Stream EnsureUnpacked(Stream s)
        {
            var reader      = new StructReader(s, System.Text.Encoding.ASCII, true);
            var streamStart = s.Position;

            var version = reader.ReadSingle(); //read just version

            s.Position = streamStart;          //back to start for further processing
            if (version >= 1.44f)
            {
                var header = reader.ReadStruct <DLF_IO_HEADER>(); //read full header

                MemoryStream ms = new MemoryStream();

                StructWriter writer = new StructWriter(ms, System.Text.Encoding.ASCII, true);
                writer.WriteStruct(header); //write header

                byte[] restOfFile = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
                byte[] unpacked   = ArxIO.Unpack(restOfFile);

                writer.Write(unpacked); //write unpacked rest
                s.Dispose();            //close old stream
                ms.Position = 0;
                return(ms);
            }
            return(s); //no need to unpack, return input stream
        }
Exemplo n.º 4
0
        public static Stream EnsureUnpacked(Stream s)
        {
            s.Position = 0;
            var reader = new StructReader(s, System.Text.Encoding.ASCII, true);

            MemoryStream ms     = new MemoryStream();
            StructWriter writer = new StructWriter(ms, System.Text.Encoding.ASCII, true);

            var header = reader.ReadStruct <FTS_IO_UNIQUE_HEADER>();

            writer.WriteStruct(header);

            for (int i = 0; i < header.count; i++)
            {
                writer.WriteStruct(reader.ReadStruct <FTS_IO_UNIQUE_HEADER2>());
            }

            byte[] restOfFile = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
            byte[] unpacked   = ArxIO.Unpack(restOfFile);

            writer.Write(unpacked); //write unpacked rest
            s.Dispose();            //close old stream
            ms.Position = 0;
            return(ms);
        }
Exemplo n.º 5
0
        public byte[] Export(string[] Strings)
        {
            uint EntryLen = (uint)Tools.GetStructLength(new Entry());

            byte[] NewScript = new byte[this.Header.TextTableOffset];
            Array.Copy(Script, NewScript, NewScript.Length);
            MemoryStream StringBuffer = new MemoryStream();

            Entry[]      EntryArr = Entries.ToArray();
            StructWriter Writer   = new StructWriter(StringBuffer, Encoding.Unicode);
            uint         Length   = 0;

            for (int i = 0; i < Strings.Length; i++)
            {
                dynamic Struct = EntryArr[i];
                Struct.TextPos       = Length;
                Struct.TextUniLength = (uint)Strings[i].Length;
                Overwrite(ref NewScript, Tools.BuildStruct(ref Struct), Header.ByteCodeLength + Header.ByteCodeStart + (EntryLen * (uint)i));
                Length += Struct.TextUniLength + 1;
                Writer.Write(Strings[i], StringStyle.UCString);
            }
            Header.TextUniTableLength = (uint)StringBuffer.Length / 2;
            Header.TextTableLength    = (uint)StringBuffer.Length;
            dynamic H = Header;

            Tools.BuildStruct(ref H).CopyTo(NewScript, 0);
            NewScript = NewScript.Concat(StringBuffer.ToArray()).ToArray();
            Writer.Close();
            StringBuffer?.Close();
            return(NewScript);
        }
Exemplo n.º 6
0
        public void WriteTo(Stream s)
        {
            using (StructWriter writer = new StructWriter(s, System.Text.Encoding.ASCII, true))
            {
                writer.WriteStruct(header);

                for (int i = 0; i < scenes.Length; i++)
                {
                    writer.WriteStruct(scenes[i]);
                }

                for (int i = 0; i < inters.Length; i++)
                {
                    writer.WriteStruct(inters[i]);
                }

                if (header.lighting != 0)
                {
                    writer.WriteStruct(lightingHeader);

                    for (int i = 0; i < lightColors.Length; i++)
                    {
                        writer.Write(lightColors[i]);
                    }
                }

                for (int i = 0; i < lights.Length; i++)
                {
                    writer.WriteStruct(lights[i]);
                }

                for (int i = 0; i < fogs.Length; i++)
                {
                    writer.WriteStruct(fogs[i]);
                }

                //write back nodes data
                writer.Write(nodesData);

                for (int i = 0; i < paths.Length; i++)
                {
                    paths[i].WriteTo(writer);
                }
            }
        }
Exemplo n.º 7
0
        public void WriteTo(StructWriter writer)
        {
            writer.WriteStruct(data);

            for (int i = 0; i < linkedAnchors.Length; i++)
            {
                writer.Write(linkedAnchors[i]);
            }
        }
Exemplo n.º 8
0
        public byte[] Export(string[] Strings)
        {
            MemoryStream Output = new MemoryStream();

            Script.Seek(0, SeekOrigin.Begin);
            CopyStream(Script.BaseStream, Output, OffsetTablePos);

            MemoryStream StrBuffer = new MemoryStream();
            StructWriter StrWorker = new StructWriter(StrBuffer, false, Encoding.Unicode);

            MemoryStream OffBuffer = new MemoryStream();
            StructWriter OffWorker = new StructWriter(OffBuffer, false, Encoding.Unicode);

            OffWorker.Write((uint)Strings.LongLength);

            for (uint i = 0; i < Strings.LongLength; i++)
            {
                StrEntry Entry = new StrEntry()
                {
                    Offset = (uint)StrBuffer.Length,
                    Length = (uint)Strings[i].Length * 2
                };
                OffWorker.WriteStruct(ref Entry);

                StrWorker.Write(Strings[i], StringStyle.UCString);
            }

            OffWorker.Write((uint)StrBuffer.Length);

            StrBuffer.Position = 0;
            OffBuffer.Position = 0;

            CopyStream(OffBuffer, Output, OffBuffer.Length);
            CopyStream(StrBuffer, Output, StrBuffer.Length);

            StrWorker.Close();
            OffWorker.Close();

            return(Output.ToArray());
        }
Exemplo n.º 9
0
        public void WriteTo(StructWriter writer)
        {
            writer.WriteStruct(data);

            for (int i = 0; i < portals.Length; i++)
            {
                writer.Write(portals[i]);
            }

            for (int i = 0; i < polygons.Length; i++)
            {
                writer.WriteStruct(polygons[i]);
            }
        }
Exemplo n.º 10
0
        public void WriteTo(StructWriter writer)
        {
            writer.WriteStruct(sceneInfo);

            for (int i = 0; i < polygons.Length; i++)
            {
                writer.WriteStruct(polygons[i]);
            }

            for (int i = 0; i < anchors.Length; i++)
            {
                writer.Write(anchors[i]);
            }
        }
Exemplo n.º 11
0
        public void WriteTo(Stream s)
        {
            StructWriter writer = new StructWriter(s, Encoding.ASCII, true);

            writer.WriteStruct(header);

            var secondaryHeaderPosition = s.Position;

            writer.WriteStruct(secondaryHeader); //write header with old values for now

            if (dataTill3Ddata != null)
            {
                writer.Write(dataTill3Ddata);
            }

            if (has3DDataSection)
            {
                secondaryHeader.offset_3Ddata = (int)s.Position;
                writer.WriteStruct(_3DDataSection);
            }
            else
            {
                secondaryHeader.offset_3Ddata = -1;
            }

            if (dataTillFileEnd != null)
            {
                writer.Write(dataTillFileEnd);
            }

            var end = s.Position;

            s.Position = secondaryHeaderPosition;
            writer.WriteStruct(secondaryHeader); //update offsets
            s.Position = end;                    //go back to end, in case user wants to do more with the stream
        }
Exemplo n.º 12
0
        private void BuildOffsetTable(int[] Offsets, out byte[] OffsetData)
        {
            MemoryStream OffData = new MemoryStream();
            StructWriter Writer  = new StructWriter(OffData);

            //Offset Count
            int OffsetSize = ForceMaxOffsetLength ? 4 : GetMinIntLen(StrCount);

            Writer.Write(ConvertSize(OffsetSize));
            Writer.Write(CreateOffset(OffsetSize, StrCount));

            //Offset's Size
            OffsetSize = ForceMaxOffsetLength ? 4 : GetMinIntLen(Offsets[StrCount - 1]);
            Writer.Write(ConvertSize(OffsetSize));

            for (int i = 0; i < StrCount; i++)
            {
                Writer.Write(CreateOffset(OffsetSize, Offsets[i]));
            }

            OffsetData = OffData.ToArray();
            Writer.Close();
            OffData?.Close();
        }
Exemplo n.º 13
0
        public byte[] Export(StringEntry[] Strings)
        {
            ScriptHeader NewHeader = new ScriptHeader();

            Tools.CopyStruct(Header, ref NewHeader);

            MemoryStream UnkData    = new MemoryStream();
            MemoryStream OffsetData = new MemoryStream();
            MemoryStream StringData = new MemoryStream();

            MemoryStream Reader = new MemoryStream(Script);

            Reader.Seek(0x10, SeekOrigin.Begin);

            Algo.CopyStream(Reader, UnkData, NewHeader.UnkCount * 8);
            Reader.Close();

            StructWriter OffsetWriter = new StructWriter(OffsetData, false, Encoding);
            StructWriter StringWriter = new StructWriter(StringData, false, Encoding);


            for (uint i = 0; i < EntryCount; i++)
            {
                OffsetWriter.Write((uint)StringWriter.BaseStream.Length);
                StringWriter.WriteStruct(ref Strings[i]);
            }
            OffsetWriter.Seek(0, SeekOrigin.Begin);
            StringWriter.Seek(0, SeekOrigin.Begin);

            NewHeader.ScriptLength = (uint)(OffsetWriter.BaseStream.Length + StringWriter.BaseStream.Length + UnkData.Length);
            NewHeader.OffsetTable  = (uint)UnkData.Length;
            NewHeader.StringTable  = (uint)(UnkData.Length + OffsetData.Length);

            byte[] Output = new byte[0x10 + UnkData.Length + OffsetData.Length + StringData.Length];

            Tools.BuildStruct(ref NewHeader, false, Encoding).CopyTo(Output, 0);

            UnkData.ToArray().CopyTo(Output, 0x10);
            OffsetData.ToArray().CopyTo(Output, 0x10 + UnkData.Length);
            StringData.ToArray().CopyTo(Output, 0x10 + UnkData.Length + OffsetData.Length);

            UnkData.Close();
            StringWriter.Close();
            OffsetWriter.Close();

            return(Compress(Output));
        }
Exemplo n.º 14
0
        private void WritePadBytes(StructWriter sw, long curlen, long wantedlen)
        {
            long padlength = wantedlen - curlen;

            if (padlength <= 0)
            {
                return;
            }


            byte[] buffer = new byte[padlength];
            for (int padidx = 0; padidx < buffer.Length; padidx++)
            {
                buffer[padidx] = 0;
            }

            sw.Write(buffer);
        }
Exemplo n.º 15
0
        public void WriteTo(Stream s)
        {
            var writer = new StructWriter(s);

            writer.WriteStruct(header);

            for (int i = 0; i < lights.Length; i++)
            {
                writer.WriteStruct(lights[i]);
            }

            writer.WriteStruct(lightingHeader);

            for (int i = 0; i < lightColors.Length; i++)
            {
                writer.Write(lightColors[i]);
            }
        }
Exemplo n.º 16
0
        public byte[] Export(string[] Text)
        {
            MemoryStream Script   = new MemoryStream(Data);
            long         StrIndex = 0;
            long         LastPos  = 0;

            byte[] Buffer = new byte[0];
            using (MemoryStream Output = new MemoryStream())
                using (StructReader Reader = new StructReader(Script, Encoding: Encoding))
                    using (StructWriter Writer = new StructWriter(Output, Encoding: Encoding)) {
                        foreach (long BasePos in BlockPos)
                        {
                            Buffer = new byte[BasePos - LastPos];
                            Reader.Read(Buffer, 0, Buffer.Length);
                            Writer.Write(Buffer, 0, Buffer.Length);

                            BINv2Struct Struct = new BINv2Struct();
                            Reader.ReadStruct(ref Struct);
                            LastPos = Reader.BaseStream.Position;

                            for (uint i = 0; i < Struct.Strings.LongLength; i++)
                            {
                                Struct.Strings[i] = Text[i + StrIndex];
                            }

                            StrIndex += Struct.Strings.LongLength;
                            Writer.WriteStruct(ref Struct);
                        }

                        if (Reader.BaseStream.Position != Reader.BaseStream.Length)
                        {
                            Reader.BaseStream.CopyTo(Writer.BaseStream);
                        }

                        Writer.Flush();
                        return(Output.ToArray());
                    }
        }
Exemplo n.º 17
0
        private void WriteNum(StructWriter Stream, long Value)
        {
            List <byte> Rst = new List <byte>();

            Rst.Add(0x00);
            while (Value-- > 0)
            {
                if (Rst[Rst.Count - 1] == 0xFF)
                {
                    Rst.Add(0x00);
                }
                Rst[Rst.Count - 1]++;
            }

            if (Rst[Rst.Count - 1] == 0xFF)
            {
                Rst.Add(0x00);
            }

            byte[] Buffer = Rst.ToArray();

            Stream.Write(Buffer, 0, Buffer.Length);
        }
Exemplo n.º 18
0
        public FieldInvoke GetStringWork()
        {
            return(new FieldInvoke(
                       (Stream, FromReader, Struct) => {
                XBXHeader Header = Struct;

                if (FromReader)
                {
                    using (StructReader Reader = new StructReader(Stream, Encoding: Encoding)) {
                        Header.Strings = new string[Header.Offsets.Length];
                        for (uint i = 0; i < Header.Offsets.Length; i++)
                        {
                            Reader.BaseStream.Position = Header.Offsets[i] + Header.StrPos;
                            if (Header.IsString[i % Header.EntryLen])
                            {
                                Header.Strings[i] = Reader.ReadString(StringStyle.CString);
                            }
                        }
                    }
                }
                else
                {
                    using (StructWriter Writer = new StructWriter(Stream, Encoding: Encoding)) {
                        Writer.BaseStream.Position = Header.StrPos;
                        for (uint i = 0; i < Header.Offsets.Length; i++)
                        {
                            if (Header.IsString[i % Header.EntryLen])
                            {
                                Writer.Write(Header.Strings[i], StringStyle.CString);
                            }
                        }
                    }
                }

                return Header;
            }));
        }
Exemplo n.º 19
0
        public byte[] Export(string[] Strs)
        {
            MemoryStream Out    = new MemoryStream();
            StructWriter Writer = new StructWriter(Out, false, Encoding.Unicode);

            Writer.Write((uint)Strs.LongLength / 2);
            for (uint i = 0; i < Strs.Length; i++)
            {
                string Str = Strs[i];
                if (EscapeMap[i])
                {
                    Str += '\0';
                }
                TMDEntry Entry = new TMDEntry()
                {
                    String = Str
                };
                Writer.WriteStruct(ref Entry);
            }
            Out.Position = 0;
            byte[] Output = Out.ToArray();
            Writer.Close();
            return(Output);
        }
Exemplo n.º 20
0
        public static string Generate(RocketPackDefinition definition, IEnumerable <RocketPackDefinition> externalDefinitions)
        {
            var w = new CodeWriter();

            // usingの宣言を行う。
            {
                var hashSet = new HashSet <string>();

                // ロードされた*.rpfファイルの名前空間をusingする
                hashSet.UnionWith(externalDefinitions.SelectMany(n => n.Options.Where(m => m.Name == "csharp_namespace").Select(m => m.Value.Trim())));

                var sortedList = hashSet.ToList();
                sortedList.Sort();

                foreach (var name in sortedList)
                {
                    w.WriteLine($"using {name};");
                }
            }

            w.WriteLine();

            w.WriteLine("#nullable enable");

            w.WriteLine();

            // namespaceの宣言を行う。
            {
                var option = definition.Options.First(n => n.Name == "csharp_namespace");

                w.WriteLine($"namespace {option.Value}");
            }

            w.WriteLine("{");
            w.PushIndent();

            var enumWriter   = new EnumWriter(definition);
            var classWriter  = new ClassWriter(definition, externalDefinitions);
            var structWriter = new StructWriter(definition, externalDefinitions);

            foreach (var enumInfo in definition.Enums)
            {
                // Enum
                enumWriter.Write(w, enumInfo);

                w.WriteLine();
            }

            foreach (var messageInfo in definition.Messages)
            {
                if (messageInfo.FormatType == MessageFormatType.Medium)
                {
                    // Class
                    classWriter.Write(w, messageInfo);
                }
                else if (messageInfo.FormatType == MessageFormatType.Small)
                {
                    // Struct
                    structWriter.Write(w, messageInfo);
                }

                w.WriteLine();
            }

            w.PopIndent();
            w.WriteLine("}");

            return(w.ToString());
        }
Exemplo n.º 21
0
        public static void Save(Stream Output, Entry[] Content, bool BigEndian, bool SteamVer, bool CloseStreams = true)
        {
            uint HeaderSize = (SteamVer ? ExNameSize : NameSize) + 4;

            StructWriter Writer  = new StructWriter(Output, BigEndian);
            object       Section = SteamVer ? (object)new SteamSection() : new Section();

            ((dynamic)Section).Name  = SteamVer ? "Filename    " : "Filename";
            ((dynamic)Section).Event = new FieldInvoke(SectionEvent);

            long        BasePos      = (uint)(Content.LongLength * 4);
            List <byte> OffsetBuffer = new List <byte>((int)BasePos);
            List <byte> NameBuffer   = new List <byte>();

            foreach (Entry Entry in Content)
            {
                OffsetBuffer.Add((uint)(NameBuffer.Count + BasePos), BigEndian);
                NameBuffer.AddRange(Encoding.UTF8.GetBytes(Entry.Filename + "\x0"));
            }

            ((dynamic)Section).Data = OffsetBuffer.Concat(NameBuffer).ToArray();

            Writer.WriteStruct(SteamVer ? typeof(SteamSection) : typeof(Section), ref Section);

            while (Writer.BaseStream.Position % (SteamVer ? 8 : 4) != 0)
            {
                Writer.Write((byte)0x00);
            }

            long PackStart = Writer.BaseStream.Position;

            ((dynamic)Section).Name = SteamVer ? "Pack        " : "Pack    ";

            List <byte> OffsetTable = new List <byte>();

            OffsetTable.Add(Content.Length, BigEndian);

            BasePos = PackStart + HeaderSize + 4 + (Content.Length * 8);

            while (BasePos % (SteamVer ? 8 : 0x100) != 0)
            {
                BasePos++;
            }

            foreach (Entry Entry in Content)
            {
                OffsetTable.Add((uint)BasePos, BigEndian);
                OffsetTable.Add((uint)Entry.Content.Length, BigEndian);
                BasePos += Entry.Content.Length;

                while (!SteamVer && BasePos % 0x100 != 0)
                {
                    BasePos++;
                }
            }

            ((dynamic)Section).Data = OffsetTable.ToArray();
            Writer.WriteStruct(SteamVer ? typeof(SteamSection) : typeof(Section), ref Section);


            while (Writer.BaseStream.Position % (SteamVer ? 8 : 0x100) != 0)
            {
                Writer.Write((byte)0);
            }


            Writer.Flush();


            foreach (Entry Entry in Content)
            {
                Entry.Content.Position = 0;
                Entry.Content.CopyTo(Output);

                while (!SteamVer && Output.Position % 0x100 != 0)
                {
                    Output.WriteByte(0);
                }
            }

            while (SteamVer && Output.Position % 0x10 != 0)
            {
                Output.WriteByte(0);
            }

            Writer.Close();
            Output?.Close();
        }
Exemplo n.º 22
0
        public byte[] Export(string[] Strings)
        {
            uint[]   Offsets = new uint[Strings.LongLength];
            Database Header  = new Database();

            Tools.ReadStruct(Script, ref Header);
            byte[] Data;
            using (MemoryStream Output = new MemoryStream()) {
                Output.Write(Script, 0, (int)Header.StringTable);
                using (StructWriter Writer = new StructWriter(Output, Encoding: GetEncoding())) {
                    //Write Strings and Generate Offset Table
                    for (uint i = 0; i < Strings.LongLength; i++)
                    {
                        Offsets[i] = (uint)(Writer.BaseStream.Position) - Header.StringTable;
                        Writer.Write(Strings[i], GetStrEnd());
                        Writer.Flush();
                    }

                    //Update StrEnd Entry of the Header
                    uint StrEnd = 0;
                    while ((StrEnd = (uint)Output.Position) % 4 != Header.StringEnd % 4)
                    {
                        Output.WriteByte(0x00);
                    }


                    //Copy Content After the String Table
                    Output.Write(Script, (int)Header.StringEnd, (int)(Script.LongLength - Header.StringEnd));

                    Header.StringEnd = StrEnd;
                    Data             = Output.ToArray();

                    //Update Offsets
                    for (uint i = Header.ValueList, OID = 0, DFID = 0; i < Header.StringTable; i += 4)
                    {
                        if (DataFormat[(int)DFID])
                        {
                            BitConverter.GetBytes(Offsets[OID++]).CopyTo(Data, i);
                        }

                        DFID++;
                        if (DFID >= DataFormat.Count)
                        {
                            DFID = 0;
                        }
                    }
                }
            }

            Tools.BuildStruct(ref Header).CopyTo(Data, 0);

            Data = Encrypt(Data);
#if !MAX && !COMP1 && !COMP2 && !COMP3 && !COMP4 && !COMP5 && !COMP6 && !COMP7 && !COMP8
            FakeCompress(ref Data);
#else
            Compress(ref Data);
#endif

            XOR(ref Data, Begin: 1);

            return(Data);
        }
Exemplo n.º 23
0
        //作者:Wetor
        //时间:2019.1.18
        public void PngToCZ1(string outfile)
        {
            Bitmap       Picture = new Bitmap(File.Open(outfile, FileMode.Open));
            StructWriter Writer  = new StructWriter(File.Open(outfile + ".cz1", FileMode.Create));
            CZ1Header    header;

            header.Signature    = "CZ1";
            header.HeaderLength = 0x10;
            header.Width        = (ushort)Picture.Width;
            header.Heigth       = (ushort)Picture.Height;
            header.Colorbits    = 4;
            Writer.WriteStruct(ref header);
            Writer.Seek(header.HeaderLength, SeekOrigin.Begin);


            Pixel32 Pixel = new Pixel32();

            Pixel.R = 255;
            Pixel.G = 255;
            Pixel.B = 255;
            //FF FF FF 00
            //FF FF FF 18
            //FF FF FF 26
            //FF FF FF 35
            //FF FF FF 45
            //FF FF FF 55
            //FF FF FF 65
            //FF FF FF 75
            //FF FF FF 85
            //FF FF FF 96
            //FF FF FF A7
            //FF FF FF B8
            //FF FF FF C9
            //FF FF FF DB
            //FF FF FF EC
            //FF FF FF FF


            Pixel.A = (byte)0x00; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x18; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x26; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x35; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x45; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x55; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x65; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x75; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x85; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0x96; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xA7; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xB8; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xC9; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xDB; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xEC; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Pixel.A = (byte)0xFF; list.Add(Pixel.A);
            Writer.WriteStruct(ref Pixel);
            Queue <byte> queue = new Queue <byte>();
            int          i     = 0;

            for (int y = 0; y < Picture.Height; y++)
            {
                for (int x = 0; x < Picture.Width; x++)
                {
                    byte tmp = color256to16(Picture.GetPixel(x, y).A);
                    //bytes11[i] = (byte)list.IndexOf(tmp);
                    queue.Enqueue((byte)list.IndexOf(tmp));
                    i++;
                }
            }

            byte[] bytes2 = new byte[Picture.Height * Picture.Width / 2];

            for (int j = 0; j < bytes2.Length; j++)
            {
                var low4bit  = queue.Dequeue();
                var high4bit = queue.Dequeue();
                var b        = (uint)(high4bit << 4) + (uint)low4bit;
                bytes2[j] = (byte)b;
            }
            //foreach (var b in bytes2)
            //{
            //    int low4bit = b & 0x0F;
            //    int high4bit = (b & 0xF0) >> 4;
            //    queue.Enqueue(low4bit);
            //    queue.Enqueue(high4bit);
            //}

            int file_num = bytes2.Length / 130554 + 1;
            //System.Diagnostics.Debug.WriteLine("{0} {1} {2}", file_num, listBytes.Count, 130554);
            List <int[]> out_list = new List <int[]>();

            Writer.Write(file_num);
            for (int k = 0; k < file_num; k++)
            {
                List <int>    listBytes    = new List <int>();
                StringBuilder decompressed = new StringBuilder();
                byte[]        tmp_bytes    = new byte[130554];
                if (k == file_num - 1)
                {
                    Array.Copy(bytes2, k * 130554, tmp_bytes, 0, bytes2.Length - k * 130554);
                }
                else
                {
                    Array.Copy(bytes2, k * 130554, tmp_bytes, 0, 130554);
                }


                foreach (char kk in tmp_bytes)
                {
                    decompressed.Append(kk);
                }
                listBytes = LzwUtil.Compress(decompressed.ToString());
                out_list.Add(listBytes.ToArray());
                Writer.Write(listBytes.Count);
                //string tmp_str;
                System.Diagnostics.Debug.WriteLine("{0}", k);

                /*if (k== file_num - 1)
                 * {
                 *  tmp_list.AddRange(listBytes.GetRange(130554 / 2 * k, listBytes.Count - 130554 / 2 * k));
                 *  tmp_list.Insert(0, 0);
                 *  tmp_str = Decompress(tmp_list);
                 * }
                 * else
                 * {
                 *  tmp_list.AddRange(listBytes.GetRange(130554 / 2 * k, 130554 / 2));
                 *  tmp_list.Insert(0, 0);
                 *  tmp_str = Decompress(tmp_list);
                 * }*/
                if (k == file_num - 1)
                {
                    Writer.Write(bytes2.Length - k * 130554);
                }
                else
                {
                    Writer.Write(130554);
                }
                //Writer.Write(0xFFFD);
            }

            /*List<byte> output = new List<byte>();
             * string str = Decompress(listBytes);
             * foreach (var c in str)
             * {
             *  output.Add((byte)c);
             * }
             * // Writer.Write(output.ToArray());
             * System.Diagnostics.Debug.WriteLine(output.Count);*/

            for (int k = 0; k < out_list.Count; k++)
            {
                for (int kk = 0; kk < out_list[k].Length; kk++)
                {
                    Writer.Write((UInt16)out_list[k][kk]);
                }
            }
            Writer.Close();
        }
Exemplo n.º 24
0
        //作者:Wetor
        //时间:2019.1.18
        public void PngToCZ1(string outfile)
        {
            Bitmap       Picture = new Bitmap(File.Open(outfile, FileMode.Open));
            StructWriter Writer  = new StructWriter(File.Open(outfile + ".cz1", FileMode.Create));
            CZ1Header    header;

            header.Signature    = "CZ1";
            header.HeaderLength = 0x10;
            header.Width        = (ushort)Picture.Width;
            header.Heigth       = (ushort)Picture.Height;
            header.Colorbits    = 8;
            Writer.WriteStruct(ref header);
            Writer.Seek(header.HeaderLength, SeekOrigin.Begin);


            Pixel32_BGRA Pixel = new Pixel32_BGRA();

            Pixel.R = 255;
            Pixel.G = 255;
            Pixel.B = 255;
            for (int k = 0; k < 256; k++)
            {
                Pixel.A = (byte)k;
                Writer.WriteStruct(ref Pixel);
            }

            byte[] bytes = new byte[Picture.Height * Picture.Width];
            int    i     = 0;

            for (int y = 0; y < Picture.Height; y++)
            {
                for (int x = 0; x < Picture.Width; x++)
                {
                    bytes[i] = Picture.GetPixel(x, y).A;
                    i++;
                }
            }


            int file_num = bytes.Length / 130554 + 1;
            //System.Diagnostics.Debug.WriteLine("{0} {1} {2}", file_num, listBytes.Count, 130554);
            List <int[]> out_list = new List <int[]>();

            Writer.Write(file_num);
            for (int k = 0; k < file_num; k++)
            {
                List <int>    listBytes    = new List <int>();
                StringBuilder decompressed = new StringBuilder();
                byte[]        tmp_bytes    = new byte[130554];
                if (k == file_num - 1)
                {
                    Array.Copy(bytes, k * 130554, tmp_bytes, 0, bytes.Length - k * 130554);
                }
                else
                {
                    Array.Copy(bytes, k * 130554, tmp_bytes, 0, 130554);
                }


                foreach (char kk in tmp_bytes)
                {
                    decompressed.Append(kk);
                }
                listBytes = LzwUtil.Compress(decompressed.ToString());
                out_list.Add(listBytes.ToArray());
                Writer.Write(listBytes.Count);
                //string tmp_str;
                System.Diagnostics.Debug.WriteLine("{0}", k);

                /*if (k== file_num - 1)
                 * {
                 *  tmp_list.AddRange(listBytes.GetRange(130554 / 2 * k, listBytes.Count - 130554 / 2 * k));
                 *  tmp_list.Insert(0, 0);
                 *  tmp_str = Decompress(tmp_list);
                 * }
                 * else
                 * {
                 *  tmp_list.AddRange(listBytes.GetRange(130554 / 2 * k, 130554 / 2));
                 *  tmp_list.Insert(0, 0);
                 *  tmp_str = Decompress(tmp_list);
                 * }*/
                if (k == file_num - 1)
                {
                    Writer.Write(bytes.Length - k * 130554);
                }
                else
                {
                    Writer.Write(130554);
                }
                //Writer.Write(0xFFFD);
            }

            /*List<byte> output = new List<byte>();
             * string str = Decompress(listBytes);
             * foreach (var c in str)
             * {
             *  output.Add((byte)c);
             * }
             * // Writer.Write(output.ToArray());
             * System.Diagnostics.Debug.WriteLine(output.Count);*/

            for (int k = 0; k < out_list.Count; k++)
            {
                for (int kk = 0; kk < out_list[k].Length; kk++)
                {
                    Writer.Write((UInt16)out_list[k][kk]);
                }
            }
            Writer.Close();
        }
Exemplo n.º 25
0
        // RequestUpdateAudioRenderer(buffer<nn::audio::detail::AudioRendererUpdateDataHeader, 5>)
        // -> (buffer<nn::audio::detail::AudioRendererUpdateDataHeader, 6>, buffer<nn::audio::detail::AudioRendererUpdateDataHeader, 6>)
        public ResultCode RequestUpdateAudioRenderer(ServiceCtx context)
        {
            long outputPosition = context.Request.ReceiveBuff[0].Position;
            long outputSize     = context.Request.ReceiveBuff[0].Size;

            MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize);

            long inputPosition = context.Request.SendBuff[0].Position;

            StructReader reader = new StructReader(context.Memory, inputPosition);
            StructWriter writer = new StructWriter(context.Memory, outputPosition);

            UpdateDataHeader inputHeader = reader.Read <UpdateDataHeader>();

            BehaviorInfo behaviorInfo = new BehaviorInfo();

            behaviorInfo.SetUserLibRevision(inputHeader.Revision);

            reader.Read <BehaviorIn>(inputHeader.BehaviorSize);

            MemoryPoolIn[] memoryPoolsIn = reader.Read <MemoryPoolIn>(inputHeader.MemoryPoolSize);

            for (int index = 0; index < memoryPoolsIn.Length; index++)
            {
                MemoryPoolIn memoryPool = memoryPoolsIn[index];

                if (memoryPool.State == MemoryPoolState.RequestAttach)
                {
                    _memoryPools[index].OutStatus.State = MemoryPoolState.Attached;
                }
                else if (memoryPool.State == MemoryPoolState.RequestDetach)
                {
                    _memoryPools[index].OutStatus.State = MemoryPoolState.Detached;
                }
            }

            _channelState = reader.Read <VoiceChannelResourceIn>(inputHeader.VoiceResourceSize);

            VoiceIn[] voicesIn = reader.Read <VoiceIn>(inputHeader.VoiceSize);

            for (int index = 0; index < voicesIn.Length; index++)
            {
                VoiceIn voice = voicesIn[index];

                VoiceContext voiceCtx = _voices[index];

                voiceCtx.SetAcquireState(voice.Acquired != 0);

                if (voice.Acquired == 0)
                {
                    continue;
                }
                voiceCtx.VoiceSlot = voice.VoiceSlot;
                // voiceCtx.ChannelState = _channelState;
                // voiceCtx.ChannelresourceID = new int[6];
                voiceCtx.ChannelresourceID[0] = voice.VoiceChannelID0;
                voiceCtx.ChannelresourceID[1] = voice.VoiceChannelID1;
                voiceCtx.ChannelresourceID[2] = voice.VoiceChannelID2;
                voiceCtx.ChannelresourceID[3] = voice.VoiceChannelID3;
                voiceCtx.ChannelresourceID[4] = voice.VoiceChannelID4;
                voiceCtx.ChannelresourceID[5] = voice.VoiceChannelID5;

                if (voice.FirstUpdate != 0)
                {
                    voiceCtx.AdpcmCtx = GetAdpcmDecoderContext(
                        voice.AdpcmCoeffsPosition,
                        voice.AdpcmCoeffsSize);

                    voiceCtx.SampleFormat  = voice.SampleFormat;
                    voiceCtx.SampleRate    = voice.SampleRate;
                    voiceCtx.ChannelsCount = voice.ChannelsCount;

                    voiceCtx.SetBufferIndex(voice.BaseWaveBufferIndex);
                }

                voiceCtx.WaveBuffers[0] = voice.WaveBuffer0;
                voiceCtx.WaveBuffers[1] = voice.WaveBuffer1;
                voiceCtx.WaveBuffers[2] = voice.WaveBuffer2;
                voiceCtx.WaveBuffers[3] = voice.WaveBuffer3;
                voiceCtx.Volume         = voice.Volume;
                voiceCtx.PlayState      = voice.PlayState;
            }

            EffectIn[] effectsIn = reader.Read <EffectIn>(inputHeader.EffectSize);

            for (int index = 0; index < effectsIn.Length; index++)
            {
                if (effectsIn[index].IsNew != 0)
                {
                    _effects[index].OutStatus.State = EffectState.New;
                }
            }

            UpdateAudio();

            UpdateDataHeader outputHeader = new UpdateDataHeader();

            int updateHeaderSize = Marshal.SizeOf <UpdateDataHeader>();

            outputHeader.Revision               = AudioRendererConsts.RevMagic;
            outputHeader.BehaviorSize           = 0xb0;
            outputHeader.MemoryPoolSize         = (_params.EffectCount + _params.VoiceCount * 4) * 0x10;
            outputHeader.VoiceSize              = _params.VoiceCount * 0x10;
            outputHeader.EffectSize             = _params.EffectCount * 0x10;
            outputHeader.SinkSize               = _params.SinkCount * 0x20;
            outputHeader.PerformanceManagerSize = 0x10;

            if (behaviorInfo.IsElapsedFrameCountSupported())
            {
                outputHeader.ElapsedFrameCountInfoSize = 0x10;
            }

            outputHeader.TotalSize = updateHeaderSize +
                                     outputHeader.BehaviorSize +
                                     outputHeader.MemoryPoolSize +
                                     outputHeader.VoiceSize +
                                     outputHeader.EffectSize +
                                     outputHeader.SinkSize +
                                     outputHeader.PerformanceManagerSize +
                                     outputHeader.ElapsedFrameCountInfoSize;

            writer.Write(outputHeader);

            foreach (MemoryPoolContext memoryPool in _memoryPools)
            {
                writer.Write(memoryPool.OutStatus);
            }

            foreach (VoiceContext voice in _voices)
            {
                writer.Write(voice.OutStatus);
            }

            foreach (EffectContext effect in _effects)
            {
                writer.Write(effect.OutStatus);
            }

            writer.SkipBytes(_params.SinkCount * 0x20);
            writer.SkipBytes(outputHeader.PerformanceManagerSize);
            writer.SkipBytes(outputHeader.BehaviorSize);

            if (behaviorInfo.IsElapsedFrameCountSupported())
            {
                writer.Write(new RendererInfoOut
                {
                    ElapsedFrameCount = _elapsedFrameCount
                });
            }

            return(ResultCode.Success);
        }
Exemplo n.º 26
0
        public void SaveFile(string filename)
        {
            // Sort the values before we save them to the sfo file
            _values.Sort();

            using (FileStream stream = File.Create(filename))
            {
                using (StructWriter sw = new StructWriter(ByteOrder.LSB, stream))
                {
                    INDEX_TABLE_ENTRY[] indexes       = new INDEX_TABLE_ENTRY[_values.Count];
                    string[]            variablenames = new string[_values.Count];

                    int  curkeynameoffset = 0;
                    uint curvalueoffset   = 0;
                    for (int idx = 0; idx < _values.Count; idx++)
                    {
                        SFOValue value = _values[idx];

                        DATA_TYPE datatype = DATA_TYPE.BinaryData;
                        uint      datasize = 0;
                        switch (value.ValueType)
                        {
                        case SFOType.Binary:
                        {
                            datatype = DATA_TYPE.BinaryData;
                            datasize = (uint)value.ValueBinary.Length;
                            break;
                        }

                        case SFOType.Int:
                        {
                            datatype = DATA_TYPE.Si32Integer;
                            datasize = 4;
                            break;
                        }

                        case SFOType.Text:
                        {
                            datatype = DATA_TYPE.Utf8Text;
                            datasize = (uint)Encoding.UTF8.GetBytes(value.ValueString).Length + 1;
                            break;
                        }

                        default:
                        {
                            throw new Exception("Unknown SFOType!");
                        }
                        }


                        indexes[idx].KeyNameOffset            = (ushort)curkeynameoffset;
                        indexes[idx].Unknown                  = 4;
                        indexes[idx].DataType                 = datatype;
                        indexes[idx].ValueDataSize            = datasize;
                        indexes[idx].ValueDataSizePlusPadding = GetPaddingSize(value.KeyName, datasize);
                        indexes[idx].DataValueOffset          = curvalueoffset;

                        variablenames[idx] = value.KeyName;

                        curkeynameoffset += value.KeyName.Length + 1;
                        curvalueoffset   += indexes[idx].ValueDataSizePlusPadding;
                    }


                    SFO_HEADER sfoheader = new SFO_HEADER();
                    sfoheader.magic           = 0;
                    sfoheader.signature       = new char[] { 'P', 'S', 'F' };
                    sfoheader.FileVersionHigh = 1;
                    sfoheader.FileVersionLow  = 1;
                    sfoheader.Unknown1        = 0;
                    sfoheader.Start_of_Variable_Name_Table = PadOffset(Marshal.SizeOf(sfoheader) + (indexes.Length * Marshal.SizeOf(typeof(INDEX_TABLE_ENTRY))));
                    sfoheader.Start_of_Variable_Data_Table = PadOffset(sfoheader.Start_of_Variable_Name_Table + curkeynameoffset);
                    sfoheader.NumberOfVariables            = (uint)_values.Count;

                    sw.WriteStruct(sfoheader);


                    // Write variable information...
                    sw.WriteStructs <INDEX_TABLE_ENTRY>(indexes);

                    WritePadBytes(sw, sw.BaseStream.Position, sfoheader.Start_of_Variable_Name_Table);

                    // Write variable names...
                    sw.WriteStrings(StringType.NullTerminated, variablenames);

                    WritePadBytes(sw, sw.BaseStream.Position, sfoheader.Start_of_Variable_Data_Table);

                    // Write variable data...
                    for (int idx = 0; idx < _values.Count; idx++)
                    {
                        SFOValue value = _values[idx];

                        switch (value.ValueType)
                        {
                        case SFOType.Binary:
                        {
                            sw.Write(value.ValueBinary);
                            break;
                        }

                        case SFOType.Int:
                        {
                            sw.Write((Int32)value.ValueInt);
                            break;
                        }

                        case SFOType.Text:
                        {
                            sw.WriteString(StringType.NullTerminated, value.ValueString);
                            break;
                        }
                        }

                        long pos = sw.BaseStream.Position;

                        WritePadBytes(sw, indexes[idx].ValueDataSize, indexes[idx].ValueDataSizePlusPadding);
                    }
                }
            }
        }
Exemplo n.º 27
0
        public long RequestUpdateAudioRenderer(ServiceCtx Context)
        {
            long OutputPosition = Context.Request.ReceiveBuff[0].Position;
            long OutputSize     = Context.Request.ReceiveBuff[0].Size;

            AMemoryHelper.FillWithZeros(Context.Memory, OutputPosition, (int)OutputSize);

            long InputPosition = Context.Request.SendBuff[0].Position;

            StructReader Reader = new StructReader(Context.Memory, InputPosition);
            StructWriter Writer = new StructWriter(Context.Memory, OutputPosition);

            UpdateDataHeader InputHeader = Reader.Read <UpdateDataHeader>();

            Reader.Read <BehaviorIn>(InputHeader.BehaviorSize);

            MemoryPoolIn[] MemoryPoolsIn = Reader.Read <MemoryPoolIn>(InputHeader.MemoryPoolSize);

            for (int Index = 0; Index < MemoryPoolsIn.Length; Index++)
            {
                MemoryPoolIn MemoryPool = MemoryPoolsIn[Index];

                if (MemoryPool.State == MemoryPoolState.RequestAttach)
                {
                    MemoryPools[Index].OutStatus.State = MemoryPoolState.Attached;
                }
                else if (MemoryPool.State == MemoryPoolState.RequestDetach)
                {
                    MemoryPools[Index].OutStatus.State = MemoryPoolState.Detached;
                }
            }

            Reader.Read <VoiceChannelResourceIn>(InputHeader.VoiceResourceSize);

            VoiceIn[] VoicesIn = Reader.Read <VoiceIn>(InputHeader.VoiceSize);

            for (int Index = 0; Index < VoicesIn.Length; Index++)
            {
                VoiceIn Voice = VoicesIn[Index];

                VoiceContext VoiceCtx = Voices[Index];

                VoiceCtx.SetAcquireState(Voice.Acquired != 0);

                if (Voice.Acquired == 0)
                {
                    continue;
                }

                if (Voice.FirstUpdate != 0)
                {
                    VoiceCtx.AdpcmCtx = GetAdpcmDecoderContext(
                        Voice.AdpcmCoeffsPosition,
                        Voice.AdpcmCoeffsSize);

                    VoiceCtx.SampleFormat  = Voice.SampleFormat;
                    VoiceCtx.SampleRate    = Voice.SampleRate;
                    VoiceCtx.ChannelsCount = Voice.ChannelsCount;

                    VoiceCtx.SetBufferIndex(Voice.BaseWaveBufferIndex);
                }

                VoiceCtx.WaveBuffers[0] = Voice.WaveBuffer0;
                VoiceCtx.WaveBuffers[1] = Voice.WaveBuffer1;
                VoiceCtx.WaveBuffers[2] = Voice.WaveBuffer2;
                VoiceCtx.WaveBuffers[3] = Voice.WaveBuffer3;
                VoiceCtx.Volume         = Voice.Volume;
                VoiceCtx.PlayState      = Voice.PlayState;
            }

            UpdateAudio();

            UpdateDataHeader OutputHeader = new UpdateDataHeader();

            int UpdateHeaderSize = Marshal.SizeOf <UpdateDataHeader>();

            OutputHeader.Revision               = IAudioRendererManager.RevMagic;
            OutputHeader.BehaviorSize           = 0xb0;
            OutputHeader.MemoryPoolSize         = (Params.EffectCount + Params.VoiceCount * 4) * 0x10;
            OutputHeader.VoiceSize              = Params.VoiceCount * 0x10;
            OutputHeader.EffectSize             = Params.EffectCount * 0x10;
            OutputHeader.SinkSize               = Params.SinkCount * 0x20;
            OutputHeader.PerformanceManagerSize = 0x10;
            OutputHeader.TotalSize              = UpdateHeaderSize +
                                                  OutputHeader.BehaviorSize +
                                                  OutputHeader.MemoryPoolSize +
                                                  OutputHeader.VoiceSize +
                                                  OutputHeader.EffectSize +
                                                  OutputHeader.SinkSize +
                                                  OutputHeader.PerformanceManagerSize;

            Writer.Write(OutputHeader);

            foreach (MemoryPoolContext MemoryPool in MemoryPools)
            {
                Writer.Write(MemoryPool.OutStatus);
            }

            foreach (VoiceContext Voice in Voices)
            {
                Writer.Write(Voice.OutStatus);
            }

            return(0);
        }
Exemplo n.º 28
0
        public override void FileImport(string path, string outpath = null)
        {
            CZ0HeaderInfo cz0HeaderInfo = null;
            string        infopath      = path.Replace(".png", ".json");

            if (File.Exists(infopath))
            {
                cz0HeaderInfo = JsonConvert.DeserializeObject <CZ0HeaderInfo>(File.ReadAllText(infopath));
            }
            CZOutputInfo czOutput = new CZOutputInfo();

            Bitmap       Picture = new Bitmap(new MemoryStream(File.ReadAllBytes(path)));
            StructWriter Writer  = new StructWriter(File.Open(path + ".cz0", FileMode.Create));
            CZ0Header    header;

            if (cz0HeaderInfo == null)
            {
                header.Signature    = "CZ0";
                header.HeaderLength = 0x40;
                header.Width        = (ushort)Picture.Width;
                header.Heigth       = (ushort)Picture.Height;
                header.Colorbits    = 32;
            }
            else
            {
                header = cz0HeaderInfo.cz0Header;
            }
            Writer.WriteStruct(ref header);
            Writer.Seek(header.HeaderLength, SeekOrigin.Begin);

            if (header.Colorbits == 32)
            {
                System.Diagnostics.Debug.WriteLine(32);
                for (int y = 0; y < Picture.Height; y++)
                {
                    for (int x = 0; x < Picture.Width; x++)
                    {
                        Writer.Write(Picture.GetPixel(x, y).R);
                        Writer.Write(Picture.GetPixel(x, y).G);
                        Writer.Write(Picture.GetPixel(x, y).B);
                        Writer.Write(Picture.GetPixel(x, y).A);
                    }
                }
            }
            else if (header.Colorbits == 24)
            {
                System.Diagnostics.Debug.WriteLine(24);
                for (int y = 0; y < Picture.Height; y++)
                {
                    for (int x = 0; x < Picture.Width; x++)
                    {
                        Writer.Write(Picture.GetPixel(x, y).R);
                        Writer.Write(Picture.GetPixel(x, y).G);
                        Writer.Write(Picture.GetPixel(x, y).B);
                    }
                }
            }
            else if (header.Colorbits == 8)
            {
                System.Diagnostics.Debug.WriteLine(8);
                List <Pixel32_BGRA> list = new List <Pixel32_BGRA>();
                for (int y = 0; y < Picture.Height; y++)
                {
                    for (int x = 0; x < Picture.Width; x++)
                    {
                        var color  = Picture.GetPixel(x, y);
                        var color2 = new Pixel32_BGRA();
                        color2.R = color.R;
                        color2.G = color.G;
                        color2.B = color.B;
                        color2.A = color.A;
                        if (!list.Contains(color2))
                        {
                            list.Add(color2);
                        }
                    }
                }

                //颜色大于256
                if (list.Count > 256)
                {
                    Console.WriteLine("Over 256 Color!!");
                    //调用pngquant png 8bit缩减
                    if (File.Exists("pngquant.exe") || File.Exists("pngquant"))
                    {
                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                        {
                            var psi = new ProcessStartInfo("pngquant.exe")
                            {
                                RedirectStandardOutput = true
                            };
                            psi.Arguments = " 256 " + path + " --ext tmp ";
                            var proc = Process.Start(psi);
                            if (proc == null)
                            {
                                Console.WriteLine("Can not exec.");
                            }
                            else
                            {
                                using (var sr = proc.StandardOutput)
                                {
                                    while (!sr.EndOfStream)
                                    {
                                        Console.WriteLine(sr.ReadLine());
                                    }

                                    if (!proc.HasExited)
                                    {
                                        proc.Kill();
                                    }
                                }
                            }
                            string pathtmp = path.Replace(".png", "tmp");
                            Picture = new Bitmap(new MemoryStream(File.ReadAllBytes(pathtmp)));
                            File.Delete(pathtmp);
                        }
                        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        {
                            //TODO
                        }
                        else
                        {
                            //TODO
                        }

                        list.Clear();
                        for (int y = 0; y < Picture.Height; y++)
                        {
                            for (int x = 0; x < Picture.Width; x++)
                            {
                                var color  = Picture.GetPixel(x, y);
                                var color2 = new Pixel32_BGRA();
                                color2.R = color.R;
                                color2.G = color.G;
                                color2.B = color.B;
                                color2.A = color.A;
                                if (!list.Contains(color2))
                                {
                                    list.Add(color2);
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Need pngquant !! Download From https://pngquant.org/");
                    }
                }

                var pixel = new Pixel32_BGRA();
                for (int i = 0; i < list.Count; i++)
                {
                    pixel = list[i];
                    Writer.WriteStruct(ref pixel);
                }
                for (int i = 0; i < 256 - list.Count; i++)
                {
                    var pixelempty = new Pixel32_BGRA()
                    {
                        R = 0, G = 0, B = 0, A = 255
                    };
                    Writer.WriteStruct(ref pixelempty);
                }

                for (int y = 0; y < Picture.Height; y++)
                {
                    for (int x = 0; x < Picture.Width; x++)
                    {
                        var color  = Picture.GetPixel(x, y);
                        var color2 = new Pixel32_BGRA();
                        color2.R = color.R;
                        color2.G = color.G;
                        color2.B = color.B;
                        color2.A = color.A;
                        uint index = (uint)list.IndexOf(color2);
                        Writer.Write((byte)index);
                    }
                }
            }
            Writer.Close();
        }
Exemplo n.º 29
0
        public long RequestUpdateAudioRenderer(ServiceCtx context)
        {
            long outputPosition = context.Request.ReceiveBuff[0].Position;
            long outputSize     = context.Request.ReceiveBuff[0].Size;

            MemoryHelper.FillWithZeros(context.Memory, outputPosition, (int)outputSize);

            long inputPosition = context.Request.SendBuff[0].Position;

            StructReader reader = new StructReader(context.Memory, inputPosition);
            StructWriter writer = new StructWriter(context.Memory, outputPosition);

            UpdateDataHeader inputHeader = reader.Read <UpdateDataHeader>();

            reader.Read <BehaviorIn>(inputHeader.BehaviorSize);

            MemoryPoolIn[] memoryPoolsIn = reader.Read <MemoryPoolIn>(inputHeader.MemoryPoolSize);

            for (int index = 0; index < memoryPoolsIn.Length; index++)
            {
                MemoryPoolIn memoryPool = memoryPoolsIn[index];

                if (memoryPool.State == MemoryPoolState.RequestAttach)
                {
                    _memoryPools[index].OutStatus.State = MemoryPoolState.Attached;
                }
                else if (memoryPool.State == MemoryPoolState.RequestDetach)
                {
                    _memoryPools[index].OutStatus.State = MemoryPoolState.Detached;
                }
            }

            reader.Read <VoiceChannelResourceIn>(inputHeader.VoiceResourceSize);

            VoiceIn[] voicesIn = reader.Read <VoiceIn>(inputHeader.VoiceSize);

            for (int index = 0; index < voicesIn.Length; index++)
            {
                VoiceIn voice = voicesIn[index];

                VoiceContext voiceCtx = _voices[index];

                voiceCtx.SetAcquireState(voice.Acquired != 0);

                if (voice.Acquired == 0)
                {
                    continue;
                }

                if (voice.FirstUpdate != 0)
                {
                    voiceCtx.AdpcmCtx = GetAdpcmDecoderContext(
                        voice.AdpcmCoeffsPosition,
                        voice.AdpcmCoeffsSize);

                    voiceCtx.SampleFormat  = voice.SampleFormat;
                    voiceCtx.SampleRate    = voice.SampleRate;
                    voiceCtx.ChannelsCount = voice.ChannelsCount;

                    voiceCtx.SetBufferIndex(voice.BaseWaveBufferIndex);
                }

                voiceCtx.WaveBuffers[0] = voice.WaveBuffer0;
                voiceCtx.WaveBuffers[1] = voice.WaveBuffer1;
                voiceCtx.WaveBuffers[2] = voice.WaveBuffer2;
                voiceCtx.WaveBuffers[3] = voice.WaveBuffer3;
                voiceCtx.Volume         = voice.Volume;
                voiceCtx.PlayState      = voice.PlayState;
            }

            UpdateAudio();

            UpdateDataHeader outputHeader = new UpdateDataHeader();

            int updateHeaderSize = Marshal.SizeOf <UpdateDataHeader>();

            outputHeader.Revision               = IAudioRendererManager.RevMagic;
            outputHeader.BehaviorSize           = 0xb0;
            outputHeader.MemoryPoolSize         = (_params.EffectCount + _params.VoiceCount * 4) * 0x10;
            outputHeader.VoiceSize              = _params.VoiceCount * 0x10;
            outputHeader.EffectSize             = _params.EffectCount * 0x10;
            outputHeader.SinkSize               = _params.SinkCount * 0x20;
            outputHeader.PerformanceManagerSize = 0x10;
            outputHeader.TotalSize              = updateHeaderSize +
                                                  outputHeader.BehaviorSize +
                                                  outputHeader.MemoryPoolSize +
                                                  outputHeader.VoiceSize +
                                                  outputHeader.EffectSize +
                                                  outputHeader.SinkSize +
                                                  outputHeader.PerformanceManagerSize;

            writer.Write(outputHeader);

            foreach (MemoryPoolContext memoryPool in _memoryPools)
            {
                writer.Write(memoryPool.OutStatus);
            }

            foreach (VoiceContext voice in _voices)
            {
                writer.Write(voice.OutStatus);
            }

            return(0);
        }
Exemplo n.º 30
0
        public static void Pack(File[] Files, Stream Output)
        {
            Header = new FPacHeader()
            {
                Signature  = 0x43415046,
                Dummy1     = 1,
                Dummy2     = 0,
                FilesCount = (uint)Files.Length
            };
            uint Tmp = 0;

            foreach (File File in Files)
            {
                if (Encoding.UTF8.GetByteCount(File.FileName) > Tmp)
                {
                    Tmp = (uint)Encoding.UTF8.GetByteCount(File.FileName);
                }
            }
            while (Tmp % 4 != 0)
            {
                Tmp++;
            }
            int EntryLen = (int)Tools.GetStructLength(new Entry(), (int)Tmp);

            while (EntryLen % 16 != 0)
            {
                EntryLen++;
            }
            uint DataLength = ((uint)EntryLen * Header.FilesCount) + (uint)Tools.GetStructLength(Header);

            Header.BaseOffset = DataLength;
            foreach (File File in Files)
            {
                DataLength += (uint)File.Data.Length;
            }
            Header.PackgetSize  = DataLength;
            Header.FilesNameLen = Tmp;
            StructWriter Writer = new StructWriter(Output, Encoding.UTF8);
            dynamic      obj    = Header;

            Writer.WriteStruct(ref obj);

            DataLength = Header.BaseOffset;
            Tmp        = 0;
            foreach (File File in Files)
            {
                dynamic Entry = new Entry()
                {
                    FileName   = File.FileName,
                    Offset     = DataLength - Header.BaseOffset,
                    Dummy      = Dummy,
                    FileIndex  = Tmp++,
                    FixPadding = Padding,
                    Length     = (uint)File.Data.Length
                };
                DataLength += (uint)File.Data.Length;
                Writer.WriteStruct(ref Entry);
            }
            DataLength = Header.BaseOffset;
            foreach (File File in Files)
            {
                int    Readed = 0;
                byte[] Buffer = new byte[1024 * 1024];
                do
                {
                    Readed = File.Data.Read(Buffer, 0, Buffer.Length);
                    Writer.Write(Buffer, 0, Readed);
                } while (Readed > 0);
                File.Data.Close();
            }
            Writer.Close();
            Output?.Close();
        }