private static void writeWmfAuxPixelData(EndianBinaryWriter writer, WmfFile file, WmfPixelInfo pixel)
 {
     if (file.header.auxDataType > 0)
     {
         writer.Write(pixel.waterTypeId);
         writer.Write(pixel.waterBodyIndex);
     }
 }
Beispiel #2
0
 protected override void Prepare(EndianBinaryWriter w)
 {
     WriteVarInt(w, (int)Version);
     WriteString8(w, Host);
     w.Write((ushort)Port);
     WriteVarInt(w, (int)State);
 }
Beispiel #3
0
        public static byte[] BuildPacket(Packets.LicensePlatePacket plateExpected)
        {
            var mem = new MemoryStream();
            var writer = new EndianBinaryWriter(Configuration.EndianBitConverter, mem, Configuration.Encoding);

            var licenseBytes = Configuration.Encoding.GetBytes(plateExpected.LicensePlate.LicenseNumber);

            writer.Write(licenseBytes);
            writer.Write(01u);
            writer.Write((UInt32)plateExpected.CaptureTime.ToBinary());
            writer.Write((UInt32)plateExpected.CaptureLocation.Id);

            int imgCount = plateExpected.EvidenceImageData.Count;
            writer.Write((uint)imgCount);

            var imgData = plateExpected.EvidenceImageData;
            for (int i = 0; i < imgCount; ++i)
            {
                writer.Write((uint)imgData[i].Length);
            }

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

            return mem.ToArray();
        }
        public byte[] ToByteArray()
        {
            using (MemoryStream buffer = new MemoryStream(100))
            {
                using (EndianBinaryWriter bw = new EndianBinaryWriter(new BigEndianBitConverter(), buffer))
                {
                    bw.Write(connection_id);
                    bw.Write(action);
                    bw.Write(transaction_id);
                    bw.Write(info_hash);
                    bw.Write(peer_id);
                    bw.Write(downloaded);
                    bw.Write(left);
                    bw.Write(uploaded);
                    bw.Write(clientEvent);
                    bw.Write(ip.GetAddressBytes());
                    bw.Write(key);
                    bw.Write(num_want);
                    bw.Write(port);
                    bw.Write(extensions);
                }

                return buffer.ToArray();
            }
        }
Beispiel #5
0
        public byte[] ToBytes()
        {
            var memory = new MemoryStream();
            var writer = new EndianBinaryWriter(EndianBitConverter.Big, memory);

            switch (Format)
            {
                case BasicHeader.HeaderFormats.F0: //11 bytes
                    writer.Write(EndianBitConverter.Big.GetBytes(TimeStamp), 1, 3);
                    writer.Write(EndianBitConverter.Big.GetBytes(MessageLength), 1, 3);
                    writer.Write((byte) MessageType);
                    writer.Write(EndianBitConverter.Little.GetBytes(MessageStreamId));
                    break;
                case BasicHeader.HeaderFormats.F1: //7 bytes
                    writer.Write(EndianBitConverter.Big.GetBytes(TimeStamp), 1, 3);
                    writer.Write(EndianBitConverter.Big.GetBytes(MessageLength), 1, 3);
                    writer.Write((byte) MessageType);
                    break;
                case BasicHeader.HeaderFormats.F2: //3 bytes
                    writer.Write(EndianBitConverter.Big.GetBytes(TimeStamp), 1, 3);
                    break;
                case BasicHeader.HeaderFormats.F3: //No bytes
                    break;
            }
            return memory.ToArray();
        }
        public void Convert(EndianBinaryWriter writer)
        {
            var jbtWriter = new JbtWriter(writer);

            var zf = new ZipFile(jarFile);

            foreach (ZipEntry ze in zf)
            {
                if (!ze.IsFile) continue;
                if (!ze.Name.EndsWith(".class")) continue;

                var type = new CompileTypeInfo();

                type.Read(zf.GetInputStream(ze));

                var reader = new BinaryReader(zf.GetInputStream(ze));

                var buffer = new byte[ze.Size];
                reader.Read(buffer, 0, (int)ze.Size);

                jbtWriter.Write(type.Name, buffer);
            }

            jbtWriter.Flush();
        }
Beispiel #7
0
        static void Update(object o)
        {
            int count = 0;
            int max = MinecraftServer.MaxSlots;
            List<string> players = new List<string>();
            foreach (Client p in PlayerList.List)
            {
                if (p.MinecraftUsername == "Player")
                    continue;
                if (p.Settings.Cloaked != null)
                    continue;
                count ++;
                players.Add(p.Name);
                if (p.Session is VanillaSession == false)
                    max ++;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                ms.WriteByte(0xff);
                EndianBinaryWriter w = new EndianBinaryWriter(EndianBitConverter.Big, ms);
                WriteString16(w, 
                    "§1\0" +
                    ((int)MinecraftServer.FrontendVersion).ToString() + "\0" +
                    MinecraftServer.FrontendVersion.ToText() + "\0" +
                    (MinecraftServer.PingReplyMessage ?? "Hi") + "\0" +
                    count + "\0" + max);

                cache = ms.ToArray();
                //Debug.WriteLine(BitConverter.ToString(cache));
            }
        }
        public void SaveGame()
        {
            if (isSaving()) {
                Log.Debug("Already doing a save: " + tempSavePath);
            }

            String name = Guid.NewGuid().ToString();

            Log.Debug("Request save: " + name);

            currentSaveData = new MemoryStream();
            BZip2Stream bzip = new BZip2Stream(currentSaveData, CompressionMode.Compress);

            saveWriter = new EndianBinaryWriter(new BigEndianBitConverter(),bzip, Encoding.UTF8);

            saveWriter.Write((byte)formatVersion);

            saveWriter.Write(Singleton<SimulationManager>.instance.m_metaData.m_CityName);
            saveWriter.Write(Singleton<EconomyManager>.instance.LastCashAmount);
            saveWriter.Write(Singleton<EconomyManager>.instance.LastCashDelta);

            int population = (int)Singleton<DistrictManager>.instance.m_districts.m_buffer[0].m_populationData.m_finalCount;
            saveWriter.Write(population);

            var timeSpan = (Singleton<SimulationManager>.instance.m_currentGameTime - new DateTime(1970, 1, 1, 0, 0, 0));
            saveWriter.Write(timeSpan.TotalSeconds);

            SavePanel savePanel = UIView.library.Get<SavePanel>("SavePanel");
            tempSavePath = Path.Combine(DataLocation.saveLocation, name + ".crp");

            savePanel.SaveGame(name);
            WaitForSave();
        }
Beispiel #9
0
 public override void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     base.Write(er, c);
     if (TextureImage != null) er.Write((uint)4);
     else er.Write((uint)0);
     if (TextureImage != null) TextureImage.Write(er, c);
 }
Beispiel #10
0
 //Constructors
 public ByteBuffer()
 {
     stream = new MemoryStream();
     bitConverter = new LittleEndianBitConverter();
     writer = new EndianBinaryWriter(bitConverter, stream);
     reader = new EndianBinaryReader(bitConverter, stream);
 }
        /// <inheritdoc/>
        public void Encode(ImageBase image, Stream stream)
        {
            Guard.NotNull(image, nameof(image));
            Guard.NotNull(stream, nameof(stream));

            int imageWidth = image.Width;
            int imageHeight = image.Height;
            ushort max = JpegConstants.MaxLength;

            if (imageWidth > max || imageHeight > max)
            {
                throw new ImageFormatException($"Image dimensions exceed maximum allowable bounds of {max}px.");
            }

            using (EndianBinaryWriter writer = new EndianBinaryWriter(new BigEndianBitConverter(), stream))
            {
                this.WriteApplicationHeader(image, writer);
                this.WriteDescreteQuantizationTables(writer);
                this.WriteStartOfFrame(image, writer);
                this.WriteHuffmanTables(writer);
                this.WriteStartOfScan(image, writer);

                writer.Write(new[] { JpegConstants.Markers.XFF, JpegConstants.Markers.EOI });
            }
        }
        public static Stream ConvertOgg(string inputFile)
        {
            if (needsConversion(inputFile))
            {
                var platform = getPlatform(inputFile);
                EndianBitConverter bitConverter = platform.GetBitConverter();

                using (var outputFileStream = new MemoryStream())
                using (var inputFileStream = File.Open(inputFile, FileMode.Open))
                using (var writer = new EndianBinaryWriter(bitConverter, outputFileStream))
                using (var reader = new EndianBinaryReader(bitConverter, inputFileStream))
                {
                    writer.Write(reader.ReadBytes(4));
                    UInt32 fileSize = reader.ReadUInt32();
                    fileSize -= 8; // We're removing data, so update the size in the header
                    writer.Write(fileSize);
                    writer.Write(reader.ReadBytes(8));
                    writer.Write(66); reader.ReadUInt32(); // New fmt size is 66
                    writer.Write(reader.ReadBytes(16));
                    writer.Write((ushort)48); reader.ReadUInt16(); // New cbSize is 48
                    writer.Write(reader.ReadBytes(6));
                    reader.BaseStream.Seek(8, SeekOrigin.Current); // Skip ahead 8 bytes, we don't want the vorb chunk
                    writer.Write(reader.ReadBytes((int)reader.BaseStream.Length - (int)reader.BaseStream.Position));

                    return new MemoryStream(outputFileStream.GetBuffer(), 0, (int)outputFileStream.Length);
                }
            }

            return File.OpenRead(inputFile);
        }
		public void testWriteString16_nullstring()
		{
			// test that a null string writes no output.
			MemoryStream stream = new MemoryStream();
			EndianBinaryWriter writer = new EndianBinaryWriter(stream);
			writer.WriteString16(null);
			Assert.AreEqual(0, stream.Length);
		}
        /*
        public static PluginMessageFromClient ParseMessage(EndianBinaryReader r)
        {
            string channel = ReadString8(r);
            int length = r.ReadInt16();
            if (length > PluginMessageFromServer.MaxDataSize)
                throw new InvalidDataException("Plugin package payload size > " + PluginMessageFromServer.MaxDataSize + " bytes");
            byte[] data = r.ReadBytesOrThrow(length);
            switch (channel)
            {
                case MCBook.ChannelEdit:
                case MCBook.ChannelSign:
                    return new MCBook(channel, data);
                case "MC|AdvCdm":
                case "MC|Beacon":
                case "MC|TPack":
                case "MC|TrList":
                case "MC|TrSel":
                case "MC|Brand":
                    return new UnknownPluginMessageClient(channel, data);
                case MCItemName.ChannelID:
                    return new UnknownPluginMessageClient(channel, data);
                default:
#if DEBUG
                    throw new InvalidOperationException("New Plugin channel: " + channel);
#else
                    return new UnknownPluginMessageClient(channel, data);
#endif
            }
        }*/

        protected override void Prepare(EndianBinaryWriter w)
        {
            /*
            WriteString8(w, Channel);
            w.Write((short)Data.Length);
            w.Write(Data);               
            */
        }
Beispiel #15
0
 public ByteBuffer(int capacity)
 {
     stream = new MemoryStream();
     bitConverter = new LittleEndianBitConverter();
     writer = new EndianBinaryWriter(bitConverter, stream);
     reader = new EndianBinaryReader(bitConverter, stream);
     stream.Capacity = capacity;
 }
Beispiel #16
0
 public override void ClearBody()
 {
     base.ClearBody();
     this.outputBuffer = null;
     this.dataIn = null;
     this.dataOut = null;
     this.length = 0;
 }
		protected override void Prepare (EndianBinaryWriter w)
		{
            throw new NotImplementedException();
			/*
            WriteString8(w, Channel);
            Varint w.Write((short)Data.Length);
            w.Write(Data);          */
		}
 protected override void Prepare(EndianBinaryWriter w)
 {
     WriteString8(w, ServerID);
     WriteVarInt(w, PublicKey.Length);
     w.Write(PublicKey);	
     WriteVarInt(w, VerifyToken.Length);
     w.Write(VerifyToken);         
 }
    //private Socket sock;
    //private IPEndPoint ipep;
    //private IPAddress ipAddr;
    /**
         * Create the server connection
         */
    public ConnectionObject(String host, int port)
    {
        tc = new TcpClient(host, port);
            tcS = tc.GetStream();

            bw = new EndianBinaryWriter(new BigEndianBitConverter(), tcS);
            br = new EndianBinaryReader(new BigEndianBitConverter(), tcS);
    }
Beispiel #20
0
 public static void Write(Tag tag, string path)
 {
     using (GZipStream gzip = new GZipStream (new FileStream (path, FileMode.Create), CompressionMode.Compress))
     {
         EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, gzip);
         tag.Write(writer);
     }
 }
 public override void ClearBody()
 {
     base.ClearBody();
     this.byteBuffer = null;
     this.dataIn = null;
     this.dataOut = null;
     this.bytesRemaining = -1;
 }
Beispiel #22
0
 static void WriteString16(EndianBinaryWriter writer, string message)
 {   
     byte[] buffer = Encoding.BigEndianUnicode.GetBytes(message);
     short length = (short)(buffer.Length / 2);
     if (message.Length != length)
         throw new InvalidProgramException();
     writer.Write(length);
     writer.Write(buffer);
 }
 protected override void Prepare(EndianBinaryWriter w)
 {
     BlockPosition.Write(w);
     w.Write((byte)FaceDirection);
     SlotItem.Write(w, this.Item);
     w.Write((byte)CursorX);
     w.Write((byte)CursorY);
     w.Write((byte)CursorZ);
 }
Beispiel #24
0
        protected RecordStrategy(TlsState state, Stream stream)
        {
            State = state;

            if (stream != null)
            {
                Reader = new EndianBinaryReader(EndianBitConverter.Big, stream);
                Writer = new EndianBinaryWriter(EndianBitConverter.Big, stream);
            }
        }
Beispiel #25
0
 public ByteBuffer(int capacity, int position, MemoryStream _stream)
 {
     stream = new MemoryStream();
     bitConverter = new LittleEndianBitConverter();
     writer = new EndianBinaryWriter(bitConverter, stream);
     reader = new EndianBinaryReader(bitConverter, stream);
     stream.Capacity = capacity;
     stream.Position = position;
     stream = _stream;
 }
Beispiel #26
0
 public override void Save()
 {
     using (
         var writer = new EndianBinaryWriter(EndianBitConverter.Big, File.Open(FilePath, FileMode.Create, FileAccess.Write),
                                             Encoding.Unicode))
     {
         writer.Write((ushort) 2);
         SaveACOData(writer);
     }
 }
Beispiel #27
0
 public ByteBuffer(Endianness _endianess, System.Text.Encoding _encoding)
 {
     stream = new MemoryStream();
     if (_endianess == Endianness.BigEndian)
         bitConverter = new BigEndianBitConverter();
     else
         bitConverter = new LittleEndianBitConverter();
     writer = new EndianBinaryWriter(bitConverter, stream, _encoding);
     reader = new EndianBinaryReader(bitConverter, stream, _encoding);
 }
        public void testWriteString16_emptystring()
        {
            // test that a null string writes no output.
            MemoryStream stream = new MemoryStream();
            EndianBinaryWriter writer = new EndianBinaryWriter(stream);
            writer.WriteString16("");

            stream.Seek(0, SeekOrigin.Begin);
            EndianBinaryReader reader = new EndianBinaryReader(stream);
            Assert.AreEqual(0, reader.ReadInt16());
        }
        protected override void Write(EndianBinaryWriter writer)
        {
            var certificates = Certificates.Select(GetBytes).ToArray();
            var totalLength = certificates.Sum(x => x.Length + 3);

            writer.WriteUInt24((uint) totalLength);
            foreach (var cert in certificates)
            {
                writer.WriteVariable(3, cert);
            }
        }
 public void testWriteString16_invalidEncodingHeader()
 {
     // Set one of the 65535 bytes to a value that will result in a 2 byte UTF8 encoded sequence.
     // This will cause the string of length 65535 to have a utf length of 65536.
     MemoryStream stream = new MemoryStream();
     EndianBinaryWriter writer = new EndianBinaryWriter(stream);
     String testStr = new String('a', 65535);
     char[] array = testStr.ToCharArray();
     array[0] = '\u0000';
     testStr = new String(array);
     writer.Write(testStr);
 }
 // NO EXAMPLES IN ROCKSMITH?
 private static void WriteRocksmithSngFretHandMuteTemplates(EndianBinaryWriter w, SongFretHandMuteTemplate[] fretHandMuteTemplates)
 {
     w.Write(new byte[4]); // placeholder
 }
Beispiel #32
0
 void ISerializableObject.Write(EndianBinaryWriter writer, object context) => Write(writer);
Beispiel #33
0
 internal override void Write(EndianBinaryWriter writer)
 {
     base.Write(writer);
     writer.Write(ListChunkName, 4);
 }
Beispiel #34
0
 protected abstract void WriteStripIndex( EndianBinaryWriter writer, ref TIndex index );
Beispiel #35
0
 public void Save(string filepath)
 {
     using (var writer = new EndianBinaryWriter(filepath, Endianness.Little))
         Write(writer);
 }
Beispiel #36
0
        public void Write(EndianBinaryWriter writer)
        {
            List <Tuple <ShapeVertexDescriptor, int> > descriptorOffsets; // Contains the offsets for each unique vertex descriptor
            List <Tuple <Packet, int> > packetMatrixOffsets;              // Contains the offsets for each packet's matrix indices
            List <Tuple <int, int> >    packetPrimitiveOffsets;           // Contains the offsets for each packet's first primitive

            long start = writer.BaseStream.Position;

            writer.Write("SHP1".ToCharArray());
            writer.Write(0); // Placeholder for section offset
            writer.Write((short)Shapes.Count);
            writer.Write((short)-1);

            writer.Write(44); // Offset to shape header data. Always 48

            for (int i = 0; i < 7; i++)
            {
                writer.Write(0);
            }

            foreach (Shape shp in Shapes)
            {
                shp.Write(writer);
            }

            // Remap table offset
            writer.Seek((int)(start + 16), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            for (int i = 0; i < Shapes.Count; i++)
            {
                writer.Write((short)i);
            }

            StreamUtility.PadStreamWithString(writer, 32);

            // Attribute descriptor data offset
            writer.Seek((int)(start + 24), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            descriptorOffsets = WriteShapeAttributeDescriptors(writer);

            // Packet matrix index data offset
            writer.Seek((int)(start + 28), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            packetMatrixOffsets = WritePacketMatrixIndices(writer);

            StreamUtility.PadStreamWithString(writer, 32);

            // Primitive data offset
            writer.Seek((int)(start + 32), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            packetPrimitiveOffsets = WritePrimitives(writer);

            // Packet matrix index metadata offset
            writer.Seek((int)(start + 36), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            foreach (Tuple <Packet, int> tup in packetMatrixOffsets)
            {
                writer.Write((short)0); // ???
                writer.Write((short)tup.Item1.MatrixIndices.Count);
                writer.Write(tup.Item2);
            }

            // Packet primitive metadata offset
            writer.Seek((int)(start + 40), System.IO.SeekOrigin.Begin);
            writer.Write((int)(writer.BaseStream.Length - start));
            writer.Seek((int)(writer.BaseStream.Length), System.IO.SeekOrigin.Begin);

            foreach (Tuple <int, int> tup in packetPrimitiveOffsets)
            {
                writer.Write(tup.Item1);
                writer.Write(tup.Item2);
            }

            StreamUtility.PadStreamWithString(writer, 32);

            writer.Seek((int)(start + 44), System.IO.SeekOrigin.Begin);

            foreach (Shape shape in Shapes)
            {
                writer.Seek(4, System.IO.SeekOrigin.Current);
                writer.Write((short)descriptorOffsets.Find(x => x.Item1 == shape.Descriptor).Item2);
                writer.Write((short)packetMatrixOffsets.IndexOf(packetMatrixOffsets.Find(x => x.Item1 == shape.Packets[0])));
                writer.Write((short)packetMatrixOffsets.IndexOf(packetMatrixOffsets.Find(x => x.Item1 == shape.Packets[0])));
                writer.Seek(30, System.IO.SeekOrigin.Current);
            }

            writer.Seek((int)writer.BaseStream.Length, System.IO.SeekOrigin.Begin);

            long end    = writer.BaseStream.Position;
            long length = (end - start);

            writer.Seek((int)start + 4, System.IO.SeekOrigin.Begin);
            writer.Write((int)length);
            writer.Seek((int)end, System.IO.SeekOrigin.Begin);
        }
Beispiel #37
0
 public void Write(EndianBinaryWriter writer)
 {
     this.Serialize((IOutputArchive) new BinaryOutputArchive(writer), string.Empty);
 }
Beispiel #38
0
 internal override void Write(EndianBinaryWriter writer)
 {
     base.Write(writer);
     Version.Write(writer);
 }
Beispiel #39
0
 protected override void WriteStripIndex( EndianBinaryWriter writer, ref StripIndexUVH2 index )
 {
     writer.Write( index.Index );
     writer.Write( index.UV );
     writer.Write( index.UV2 );
 }
        // COMPLETE except hardcoded fields
        private static void WriteRocksmithSngLevelNotes(EndianBinaryWriter w, List <PhraseIterationInfo> iterationInfo, SongNote[] notes, SongChord[] chords, Single songLength, ArrangementType arrangementType)
        {
            List <TimeLinkedEntity> notesChords = new List <TimeLinkedEntity>();

            // add notes to combined note/chord array
            if (notes != null && notes.Length != 0)
            {
                notesChords.AddRange(notes.Select(note =>
                                                  new TimeLinkedEntity
                {
                    Time   = note.Time,
                    Entity = note
                }));
            }

            // add chords to combined note/chord array
            if (chords != null && chords.Length != 0)
            {
                notesChords.AddRange(chords.Select(chord =>
                                                   new TimeLinkedEntity
                {
                    Time   = chord.Time,
                    Entity = chord
                }));
            }

            // sort the notes and chords by time
            notesChords.Sort((s1, s2) => s1.Time.CompareTo(s2.Time));

            // write empty header if no notes or chords
            if (notesChords.Count == 0)
            {
                w.Write(new byte[4]); // empty header
                return;
            }

            // output notes and chords header count
            w.Write(notesChords.Count);

            // ouput notes and chords
            for (int i = 0; i < (notesChords.Count); i++)
            {
                // note time tag
                w.Write(notesChords[i].Time);

                // string tag
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).String : -1);

                // fret tag
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Fret : (sbyte)-1);

                // chord id
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? -1 : ((SongChord)notesChords[i].Entity).ChordId);

                // unknown
                w.Write(Convert.ToInt32(-1));

                // sustain time
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Sustain : 0);

                // bend
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Bend : (byte)0);

                // slideTo
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).SlideTo : (sbyte)-1);

                // tremolo
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Tremolo : new byte());

                // harmonic
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Harmonic : new byte());

                // palm mute
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).PalmMute : new byte());

                if (arrangementType == ArrangementType.Bass)
                {
                    w.Write(new byte());//unknownB

                    //Bass only - Slap
                    w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Slap : (sbyte)-1);

                    //Bass only - Pluck
                    w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Pluck : (sbyte)-1);
                }

                // hopo
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Hopo : new byte());

                // hammerOn
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).HammerOn : new byte());

                // pullOff
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).PullOff : new byte());

                // ignore
                w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? ((SongNote)notesChords[i].Entity).Ignore : ((SongChord)notesChords[i].Entity).Ignore);

                // high density chord
                if (arrangementType == ArrangementType.Bass)
                {
                    w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? new byte() : (byte)((SongChord)notesChords[i].Entity).HighDensity);
                    w.Write(new byte());
                    w.Write((byte)140);
                    w.Write(new byte());
                }
                else
                {
                    w.Write(notesChords[i].Entity.GetType() == typeof(SongNote) ? new byte() : ((SongChord)notesChords[i].Entity).HighDensity);
                    w.Write(new byte[4]);
                }

                //w.Write(Convert.ToInt16(246));
                //w.Write(Convert.ToInt16(7472));

                // phrase iteration start index and id ????
                bool phraseStartIterationFound = false;
                foreach (var iteration in iterationInfo)
                {
                    if (notesChords[i].Time >= iteration.StartTime && notesChords[i].Time < iteration.EndTime)
                    {
                        w.Write(iteration.IterationId); // phrase iteration
                        w.Write(iteration.PhraseId);
                        phraseStartIterationFound = true;
                        break;
                    }
                }
                if (!phraseStartIterationFound)
                {
                    throw new Exception(string.Format("No phrase start iteration found with matching time for note {0}.", i.ToString()));
                }
            }
        }
        protected override void writeAsm(EndianBinaryWriter stream, AddressMapper addressMapper, List <MapDescriptor> mapDescriptors)
        {
            // this is the virtual address for the ForceVentureCardVariable: 0x804363c4
            // instead of allocating space for the venture card variable with the free space manager, we use a fixed virtual address
            // so that this variable can be reused by other hacks outside of CSMM.
            var forceVentureCardVariable = addressMapper.toVersionAgnosticAddress((BSVAddr)0x804363c4);

            stream.Seek(addressMapper.toFileAddress(forceVentureCardVariable), SeekOrigin.Begin);
            // write zeroes to it
            stream.Write(new byte[4]);

            // --- Model ---
            // some examples:
            //   80087f88 = Property
            //   80088040 = Bank
            //   80088100 = Default
            //   80088050 = Take a break
            //   80088068 = Stockbroker
            //   80088048 = Arcade
            //   80088060 = Switch
            //   80088058 = Cannon
            stream.Seek(addressMapper.toFileAddress((BSVAddr)0x80453330), SeekOrigin.Begin);
            stream.Write((UInt32)addressMapper.toVersionAgnosticAddress((BSVAddr)0x80088060));

            // --- Texture ---
            var customTextureHandler = allocate(writeGetTextureForCustomSquareRoutine(15, 14), "GetTextureForCustomSquareRoutine");
            var virtualPos           = addressMapper.toVersionAgnosticAddress((BSVAddr)0x80086d98);

            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // li r15,0x1        -> bl customTextureHandler
            stream.Write(PowerPcAsm.bl(virtualPos, customTextureHandler));

            customTextureHandler = allocate(writeGetTextureForCustomSquareRoutine(31, 30), "GetTextureForCustomSquareRoutine2");
            virtualPos           = addressMapper.toVersionAgnosticAddress((BSVAddr)0x80087a24);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // li r31,0x1        -> bl customTextureHandler
            stream.Write(PowerPcAsm.bl(virtualPos, customTextureHandler));

            // --- Icon ---
            stream.Seek(addressMapper.toFileAddress((BSVAddr)0x804160c8), SeekOrigin.Begin);
            stream.Write((uint)addressMapper.toVersionAgnosticAddress((BSVAddr)0x80415ee0)); // pointer to the texture name (0x80415ee0 points to the string "p_mark_21" which is the switch icon texture
            stream.Write((uint)addressMapper.toVersionAgnosticAddress((BSVAddr)0x80415ee0)); // we need to write it twice: once for each design type (Mario and DragonQuest)

            // --- Name ---
            stream.Seek(addressMapper.toFileAddress((BSVAddr)0x80475580), SeekOrigin.Begin);
            stream.Write(3336); // id of the message in ui_message.csv (3336 = "Switch square")

            // --- Description ---
            var customDescriptionRoutine = allocate(writeGetDescriptionForCustomSquareRoutine(addressMapper, (VAVAddr)0), "GetDescriptionForCustomSquareRoutine");

            stream.Seek(addressMapper.toFileAddress(customDescriptionRoutine), SeekOrigin.Begin);
            stream.Write(writeGetDescriptionForCustomSquareRoutine(addressMapper, customDescriptionRoutine)); // re-write the routine again since now we know where it is located in the main dol

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8ce4);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8d6c);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8dd8);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8e5c);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8ee4);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x800f8f4c);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // bl Game::uitext::get_string   -> bl customDescriptionRoutine
            stream.Write(PowerPcAsm.bl(virtualPos, customDescriptionRoutine));

            // --- Behavior ---
            // the idea is that whenever someone stops at the event square, it sets our custom variable "ForceVentureCardVariable" to the id of the venture card and runs the Venture Card Mode (0x1c).
            // The custom variable is used to remember which venture card should be played the next time a venture card is executed.
            var procStopEventSquareRoutine = allocate(writeProcStopEventSquareRoutine(addressMapper, forceVentureCardVariable, (VAVAddr)0), "procStopEventSquareRoutine");

            stream.Seek(addressMapper.toFileAddress(procStopEventSquareRoutine), SeekOrigin.Begin);
            stream.Write(writeProcStopEventSquareRoutine(addressMapper, forceVentureCardVariable, procStopEventSquareRoutine)); // re-write the routine again since now we know where it is located in the main dol

            stream.Seek(addressMapper.toFileAddress((BSVAddr)0x80475838), SeekOrigin.Begin);
            stream.Write((UInt32)procStopEventSquareRoutine);

            // --- Hijack Venture Card Mode ---
            // We are hijacking the execute venture card mode (0x1f) to check if our custom variable "ForceVentureCardVariable" has been set to anything other than 0.
            // If it was, then setup that specific venture card to be executed. Also reset our custom variable "ForceVentureCardVariable" so that normal venture cards still work.
            var forceFetchFakeVentureCard = allocate(writeSubroutineForceFetchFakeVentureCard(forceVentureCardVariable), "forceFetchFakeVentureCard");

            virtualPos = addressMapper.toVersionAgnosticAddress((BSVAddr)0x801b7f44);
            stream.Seek(addressMapper.toFileAddress(virtualPos), SeekOrigin.Begin);
            // li r4,-0x1   -> bl forceFetchFakeVentureCard
            stream.Write(PowerPcAsm.bl(virtualPos, forceFetchFakeVentureCard));
            // li r8,0x3    -> nop
            stream.Seek(addressMapper.toFileAddress((BSVAddr)0x801b7f74), SeekOrigin.Begin);
            stream.Write(PowerPcAsm.nop());
        }
Beispiel #42
0
 /// <summary>
 /// Writes the graphics control extension to the stream.
 /// </summary>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 /// <param name="imageFrame">The <see cref="ImageFrame{TPixel}"/> to encode.</param>
 /// <param name="writer">The stream to write to.</param>
 /// <param name="transparencyIndex">The index of the color in the color palette to make transparent.</param>
 private void WriteGraphicalControlExtension <TPixel>(ImageFrame <TPixel> imageFrame, EndianBinaryWriter writer, int transparencyIndex)
     where TPixel : struct, IPixel <TPixel>
 {
     this.WriteGraphicalControlExtension(imageFrame, imageFrame.MetaData, writer, transparencyIndex);
 }
Beispiel #43
0
 /// <summary>
 /// Writes the file header signature and version to the stream.
 /// </summary>
 /// <param name="writer">The writer to write to the stream with.</param>
 private void WriteHeader(EndianBinaryWriter writer)
 {
     writer.Write((GifConstants.FileType + GifConstants.FileVersion).ToCharArray());
 }
Beispiel #44
0
 public override void ToBinaryWriter(EndianBinaryWriter writer)
 {
     writer.Write(A);
     writer.Write(B);
 }
 // COMPLETE
 private static void WriteRocksmithSngHeader(EndianBinaryWriter w, ArrangementType arrangementType)
 {
     w.Write(arrangementType == ArrangementType.Bass ? 51 : 49); // version num?
 }
Beispiel #46
0
        private List <Tuple <ShapeVertexDescriptor, int> > WriteShapeAttributeDescriptors(EndianBinaryWriter writer)
        {
            List <Tuple <ShapeVertexDescriptor, int> > outList = new List <Tuple <ShapeVertexDescriptor, int> >();
            List <ShapeVertexDescriptor> written = new List <ShapeVertexDescriptor>();

            long start = writer.BaseStream.Position;

            foreach (Shape shape in Shapes)
            {
                if (written.Contains(shape.Descriptor))
                {
                    continue;
                }
                else
                {
                    outList.Add(new Tuple <ShapeVertexDescriptor, int>(shape.Descriptor, (int)(writer.BaseStream.Position - start)));
                    shape.Descriptor.Write(writer);
                    written.Add(shape.Descriptor);
                }
            }

            return(outList);
        }
        // INCOMPLETE
        private static void WriteRocksmithSngMetaDetails(EndianBinaryWriter w, Song s, InstrumentTuning tuning, List <PhraseIterationInfo> iterationInfo)
        {
            // Max score when fully leveled (minus bonuses - always 100000).  Or possible Master mode unlock score
            w.Write((double)100000);

            //This needs to be calculated to take real charts into account.
            double totalNotes = 0;

            foreach (var iteration in iterationInfo)
            {
                if (s.Levels.Length <= iteration.MaxDifficulty)
                {
                    throw new Exception("There is a phrase defined with maxDifficulty=" + iteration.MaxDifficulty + ", but the highest difficulty level is " + (s.Levels.Length - 1));
                }
                var level = s.Levels[iteration.MaxDifficulty];
                if (level.Notes != null)
                {
                    totalNotes += level.Notes.Where(note => note.Time >= iteration.StartTime && note.Time < iteration.EndTime).Count();
                }
                if (level.Chords != null)
                {
                    totalNotes += level.Chords.Where(chord => chord.Time >= iteration.StartTime && chord.Time < iteration.EndTime).Count();
                }
            }
            // Total notes when fully leveled
            w.Write(totalNotes);

            // points per note
            w.Write((double)((float)(100000f / (float)totalNotes)));

            // song beat timing
            if (s.Ebeats.Length < 2)
            {
                throw new InvalidDataException("Song must contain at least 2 beats");
            }

            // this is not 100% accurate unless all beats are evenly spaced in a song;
            // still trying to determine exactly how Rocksmith is deriving this time value
            w.Write(s.Ebeats[1].Time - s.Ebeats[0].Time);

            // first beat time(?); confirmed as not first phraseIteration time and not first section time
            w.Write(s.Ebeats[0].Time);

            // song conversion date
            var lastConvertDate = s.LastConversionDateTime;

            if (lastConvertDate.Length > 32)
            {
                lastConvertDate = lastConvertDate.Substring(0, 32);
            }
            foreach (char c in lastConvertDate)
            {
                w.Write(Convert.ToByte(c));
            }
            w.Write(new byte[32 - lastConvertDate.Length]); //pad to 32 bytes

            // song title
            var title = s.Title;

            if (title.Length > 64)
            {
                title = title.Substring(0, 64);
            }
            foreach (char c in title)
            {
                w.Write(Convert.ToByte(c));
            }
            w.Write(new byte[64 - title.Length]); // pad to 64 bytes

            // arrangement
            var arrangement = s.Arrangement;

            if (arrangement.Length > 32)
            {
                arrangement = arrangement.Substring(0, 32);
            }
            foreach (char c in arrangement)
            {
                w.Write(Convert.ToByte(c));
            }
            w.Write(new byte[32 - arrangement.Length]); //pad to 32 bytes

            // artist
            string artistValue = string.IsNullOrEmpty(s.Artist) ? "DUMMY" : s.Artist;

            if (artistValue.Length > 32)
            {
                artistValue = artistValue.Substring(0, 32);
            }
            foreach (char c in artistValue)
            {
                w.Write(Convert.ToByte(c));
            }
            w.Write(new byte[32 - artistValue.Length]); //pad to 32 bytes

            // song part
            w.Write(s.Part);

            // song length
            w.Write(s.SongLength);

            // tuning
            w.Write((Int32)tuning);

            //Song difficulty
            float difficulty = (float)iterationInfo.Average(it => it.MaxDifficulty);

            w.Write(difficulty); // float with 10.2927 in NumberThirteen_Lead.sng

            // unknown
            // from 6AMSalvation_Combo.xml value = 11.525
            // which does not match any pharse iteration start time
            // and does not match first ebeat time
            // and does not match any section start time
            // does match first event time of E3 (although this is not a match in other files)
            // does not match any note times on 1st difficulty level
            // nor an anchor time on 1st difficulty level

            //It appears to be the time of the first note.
            float firstNote  = s.Levels.Min(level => level.Notes == null || level.Notes.Length == 0 ? float.MaxValue : level.Notes.Min(note => note.Time));
            float firstChord = s.Levels.Min(level => level.Chords == null || level.Chords.Length == 0 ? float.MaxValue : level.Chords.Min(chord => chord.Time));
            float first      = Math.Min(firstChord, firstNote);

            w.Write(first);

            w.Write(first);

            // max difficulty
            int maxDifficulty = s.Levels.Length - 1;

            w.Write(maxDifficulty);

            // unknown section
            w.Write(new byte[4]); // header with repeating array; song works in game if array is defaulted to 0 count so will leave this alone for now

            // unknown section
            // There seems to be 1 entry per letter in the chord templates, although there are songs with chord templates that don't have this section.
            w.Write(new byte[4]); // header with repeating array - only populated in limited songs
        }
Beispiel #48
0
 public void Write(EndianBinaryWriter writer)
 {
     writer.Write(DataBytes);
 }
Beispiel #49
0
 protected override void WriteStripIndex( EndianBinaryWriter writer, ref StripIndexVN index )
 {
     writer.Write( index.Index );
     writer.Write( index.Normal );
 }
 public void Write(EndianBinaryWriter ew)
 {
     throw new NotImplementedException();
 }
 protected override void Prepare(EndianBinaryWriter w)
 {
     w.Write((byte)Difficulty);
 }
        // INCOMPLETE
        // section begins at @ 9,820 in NumberThirteen_Lead.sng
        private static void WriteRocksmithSngLevels(EndianBinaryWriter w, Xml.SongLevel[] levels, Single songLength, List <PhraseIterationInfo> iterationInfo, ArrangementType arrangementType)
        {
            // output header
            if (levels == null || levels.Length == 0)
            {
                w.Write(new byte[4]); // empty header
                return;
            }

            // output header count
            w.Write(levels.Length);

            // output
            foreach (var level in levels)
            {
                // level difficulty tag
                w.Write(level.Difficulty);

                // anchors
                WriteRocksmithSngLevelAnchors(w, level.Anchors, level, iterationInfo, songLength);

                // slide properties
                WriteRockmithSngLevelSlideProperties(w, level.Notes);

                // handshapes
                WriteRocksmithSngLevelHandShapes(w, level.HandShapes, level, songLength);

                // notes and chords
                WriteRocksmithSngLevelNotes(w, iterationInfo, level.Notes, level.Chords, songLength, arrangementType);

                var iterationNotes = new List <int>();
                foreach (var iteration in iterationInfo)
                {
                    int num = 0;
                    if (level.Notes != null)
                    {
                        num += level.Notes.Where(n => n.Time >= iteration.StartTime && n.Time < iteration.EndTime).Count();
                    }
                    if (level.Chords != null)
                    {
                        num += level.Chords.Where(n => n.Time >= iteration.StartTime && n.Time < iteration.EndTime).Count();
                    }
                    iterationNotes.Add(num);
                }

                var phrases = iterationInfo.GroupBy(it => it.PhraseId).OrderBy(grp => grp.Key);;
                // count of phrases
                w.Write(phrases.Count());
                foreach (var phrase in phrases)
                {
                    float notes = (float)phrase.Sum(iteration => iterationNotes[iteration.IterationId]);
                    float count = phrase.Count();

                    w.Write(notes / count); // This is the number of notes + chords in all iterations of this phrase for this level, divided by number of iterations of this phrase
                }

                // count of phrase iterations
                w.Write(iterationInfo.Count);
                foreach (var iterationNoteCount in iterationNotes)
                {
                    w.Write(iterationNoteCount);// This appears to be the number of notes + chords in each iteration for this level
                }

                // count of phrase iterations
                w.Write(iterationInfo.Count);
                foreach (var iterationNoteCount in iterationNotes)
                {
                    w.Write(iterationNoteCount);// This appears to be the number of notes + chords in each iteration for this level
                }
            }
        }
Beispiel #53
0
 protected override void WriteStripIndex( EndianBinaryWriter writer, ref StripIndexD8 index )
 {
     writer.Write( index.Index );
     writer.Write( index.Color );
 }
        // COMPLETE except hardcoded fields
        // Sample: begins at position 9,216 in NumberThirteen_Lead.sng
        private static void WriteRocksmithSngSections(EndianBinaryWriter w, Xml.SongSection[] sections, SongPhraseIteration[] phraseIterations, Single songLength)
        {
            // output header
            if (sections == null || sections.Length == 0)
            {
                w.Write(new byte[4]); // empty header
                return;
            }
            // output header count
            w.Write(sections.Length);

            // output sections
            for (int i = 0; i < sections.Length; i++)
            {
                // section name
                string name = sections[i].Name;
                if (name.Length > 32)
                {
                    name = name.Substring(0, 32);
                }
                foreach (char c in name)
                {
                    w.Write(Convert.ToByte(c));
                }
                // padding after section name
                w.Write(new byte[32 - name.Length]);

                // number tag
                w.Write(sections[i].Number);

                // start time
                w.Write(sections[i].StartTime);

                // end time
                var endTime = i == sections.Length - 1
                    ? songLength
                    : sections[i + 1].StartTime;
                w.Write(endTime);

                // phrase iteration start index
                bool phraseIterationFound = false;
                for (int p = 0; p < phraseIterations.Length; p++)
                {
                    if (sections[i].StartTime <= phraseIterations[p].Time)
                    {
                        w.Write(p);
                        phraseIterationFound = true;
                        break;
                    }
                }
                if (!phraseIterationFound)
                {
                    throw new Exception(string.Format("No phrase iteration found with matching time for section {0}.", i.ToString()));
                }

                // phrase iteration end index
                if (i == sections.Length - 1) // if last section, default to last phrase iteration
                {
                    w.Write(phraseIterations.Length - 1);
                }
                else
                {
                    //bool endPhraseIterationFound = false;
                    for (int p = 0; p < phraseIterations.Length; p++)
                    {
                        if (sections[i + 1].StartTime <= phraseIterations[p].Time)
                        {
                            w.Write(Convert.ToInt32(p - 1));
                            //endPhraseIterationFound = true;
                            break;
                        }
                    }
                    //if (!endPhraseIterationFound)
                    //    throw new Exception(string.Format("No end phrase iteration found with matching time for section {0}.", i.ToString()));
                }

                // series of 8 unknown bytes (look like flags)? below logic is wrong, just defaulting for now
                w.Write(true);
                w.Write(true);
                w.Write(true);
                w.Write(true);
                w.Write(true);
                w.Write(false);
                w.Write(false);
                w.Write(false);
            }
        }
Beispiel #55
0
        /// <summary>
        /// Writes the graphics control extension to the stream.
        /// </summary>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        /// <param name="image">The <see cref="ImageBase{TPixel}"/> to encode.</param>
        /// <param name="metaData">The metadata of the image or frame.</param>
        /// <param name="writer">The stream to write to.</param>
        /// <param name="transparencyIndex">The index of the color in the color palette to make transparent.</param>
        private void WriteGraphicalControlExtension <TPixel>(ImageBase <TPixel> image, IMetaData metaData, EndianBinaryWriter writer, int transparencyIndex)
            where TPixel : struct, IPixel <TPixel>
        {
            GifGraphicsControlExtension extension = new GifGraphicsControlExtension()
            {
                DisposalMethod    = metaData.DisposalMethod,
                TransparencyFlag  = transparencyIndex < 255,
                TransparencyIndex = transparencyIndex,
                DelayTime         = metaData.FrameDelay
            };

            // Write the intro.
            this.buffer[0] = GifConstants.ExtensionIntroducer;
            this.buffer[1] = GifConstants.GraphicControlLabel;
            this.buffer[2] = 4;
            writer.Write(this.buffer, 0, 3);

            PackedField field = default(PackedField);

            field.SetBits(3, 3, (int)extension.DisposalMethod); // 1-3 : Reserved, 4-6 : Disposal

            // TODO: Allow this as an option.
            field.SetBit(6, false);                      // 7 : User input - 0 = none
            field.SetBit(7, extension.TransparencyFlag); // 8: Has transparent.

            writer.Write(field.Byte);
            writer.Write((ushort)extension.DelayTime);
            writer.Write((byte)extension.TransparencyIndex);
            writer.Write(GifConstants.Terminator);
        }
Beispiel #56
0
 protected override void Prepare(EndianBinaryWriter w)
 {
     WriteVarInt(w, EID);
     Metadata.Write(w, Metadata);
 }
Beispiel #57
0
        /// <summary>
        /// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>.
        /// </summary>
        /// <typeparam name="TPixel">The pixel format.</typeparam>
        /// <param name="image">The <see cref="Image{TPixel}"/> to encode from.</param>
        /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param>
        public void Encode <TPixel>(Image <TPixel> image, Stream stream)
            where TPixel : struct, IPixel <TPixel>
        {
            Guard.NotNull(image, nameof(image));
            Guard.NotNull(stream, nameof(stream));

            this.Quantizer = this.options.Quantizer ?? new OctreeQuantizer <TPixel>();

            // Do not use IDisposable pattern here as we want to preserve the stream.
            EndianBinaryWriter writer = new EndianBinaryWriter(Endianness.LittleEndian, stream);

            // Ensure that quality can be set but has a fallback.
            int quality = this.options.Quality > 0 ? this.options.Quality : image.MetaData.Quality;

            quality = quality > 0 ? quality.Clamp(1, 256) : 256;

            // Get the number of bits.
            this.bitDepth = ImageMaths.GetBitsNeededForColorDepth(quality);

            // Quantize the image returning a palette.
            this.hasFrames = image.Frames.Any();

            // Dithering when animating gifs is a bad idea as we introduce pixel tearing across frames.
            IQuantizer <TPixel> ditheredQuantizer = (IQuantizer <TPixel>) this.Quantizer;

            ditheredQuantizer.Dither = !this.hasFrames;

            QuantizedImage <TPixel> quantized = ditheredQuantizer.Quantize(image, quality);

            int index = this.GetTransparentIndex(quantized);

            // Write the header.
            this.WriteHeader(writer);

            // Write the LSD. We'll use local color tables for now.
            this.WriteLogicalScreenDescriptor(image, writer, index);

            // Write the first frame.
            this.WriteGraphicalControlExtension(image, writer, index);
            this.WriteComments(image, writer);
            this.WriteImageDescriptor(image, writer);
            this.WriteColorTable(quantized, writer);
            this.WriteImageData(quantized, writer);

            // Write additional frames.
            if (this.hasFrames)
            {
                this.WriteApplicationExtension(writer, image.MetaData.RepeatCount, image.Frames.Count);

                // ReSharper disable once ForCanBeConvertedToForeach
                for (int i = 0; i < image.Frames.Count; i++)
                {
                    ImageFrame <TPixel>     frame          = image.Frames[i];
                    QuantizedImage <TPixel> quantizedFrame = ditheredQuantizer.Quantize(frame, quality);

                    this.WriteGraphicalControlExtension(frame, writer, this.GetTransparentIndex(quantizedFrame));
                    this.WriteImageDescriptor(frame, writer);
                    this.WriteColorTable(quantizedFrame, writer);
                    this.WriteImageData(quantizedFrame, writer);
                }
            }

            // TODO: Write extension etc
            writer.Write(GifConstants.EndIntroducer);
        }
Beispiel #58
0
        static void Handle(object client_obj)
        {
            string       name = Thread.CurrentThread.Name;
            StreamWriter log  = null;

            try
            {
                TcpClient client = (TcpClient)client_obj;
                using (NetworkStream stream = client.GetStream())
                {
                    EndianBinaryReader reader = new EndianBinaryReader(stream);
                    EndianBinaryWriter writer = new EndianBinaryWriter(stream);

                    uint[] ids = reader.ReadUInt32s(4);

                    // Log connection
                    Console.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    Console.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    // Create log file for current thread
                    log = new StreamWriter(logs_root + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + "-" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + ".txt");
                    log.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    log.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    writer.Write(BYTE_SPECIAL);

                    while (true)
                    {
                        byte cmd_byte = reader.ReadByte();
                        switch (cmd_byte)
                        {
                        case BYTE_OPEN_FILE:
                        case BYTE_OPEN_FILE_ASYNC:
                        {
                            int    len_path = reader.ReadInt32();
                            int    len_mode = reader.ReadInt32();
                            string path     = reader.ReadString(Encoding.ASCII, len_path - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }
                            string mode = reader.ReadString(Encoding.ASCII, len_mode - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }

                            if (cmd_byte == BYTE_OPEN_FILE)
                            {
                                Log(log, name + " FSOpenFile(\"" + path + "\", \"" + mode + "\")");
                            }
                            else
                            {
                                Log(log, name + " FSOpenFileAsync(\"" + path + "\", \"" + mode + "\")");
                            }

                            break;
                        }

                        case BYTE_READ_FILE:
                        case BYTE_READ_FILE_ASYNC:
                        {
                            int size  = reader.ReadInt32();
                            int count = reader.ReadInt32();
                            int fd    = reader.ReadInt32();

                            if (cmd_byte == BYTE_READ_FILE)
                            {
                                Log(log, name + " FSReadFile(size=" + size.ToString() + ", count=" + count.ToString() + ", fd=" + fd.ToString() + ")");
                            }
                            else
                            {
                                Log(log, name + " FSReadFileAsync(size=" + size.ToString() + ", count=" + count.ToString() + ", fd=" + fd.ToString() + ")");
                            }

                            break;
                        }

                        case BYTE_CLOSE_FILE:
                        case BYTE_CLOSE_FILE_ASYNC:
                        {
                            int fd = reader.ReadInt32();

                            if (cmd_byte == BYTE_CLOSE_FILE)
                            {
                                Log(log, name + " FSCloseFile(" + fd.ToString() + ")");
                            }
                            else
                            {
                                Log(log, name + " FSCloseFileAsync(" + fd.ToString() + ")");
                            }

                            break;
                        }

                        case BYTE_SETPOS:
                        {
                            int fd  = reader.ReadInt32();
                            int pos = reader.ReadInt32();

                            Log(log, name + " FSSetPos(fd=" + fd.ToString() + ", pos=" + pos.ToString() + ")");

                            break;
                        }

                        case BYTE_STATFILE:
                        {
                            int fd = reader.ReadInt32();
                            Log(log, name + " FSGetStatFile(" + fd.ToString() + ")");

                            break;
                        }

                        case BYTE_OPEN_DIR:
                        case BYTE_OPEN_DIR_ASYNC:
                        {
                            int    len_path = reader.ReadInt32();
                            string path     = reader.ReadString(Encoding.ASCII, len_path - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }

                            if (cmd_byte == BYTE_OPEN_DIR)
                            {
                                Log(log, name + " FSOpenDir(\"" + path + "\")");
                            }
                            else
                            {
                                Log(log, name + " FSOpenDirAsync(\"" + path + "\")");
                            }

                            break;
                        }

                        case BYTE_READ_DIR:
                        case BYTE_READ_DIR_ASYNC:
                        {
                            int fd = reader.ReadInt32();

                            if (cmd_byte == BYTE_READ_DIR)
                            {
                                Log(log, name + " FSReadDir(fd=" + fd.ToString() + ")");
                            }
                            else
                            {
                                Log(log, name + " FSReadDirAsync(fd=" + fd.ToString() + ")");
                            }

                            break;
                        }

                        case BYTE_CLOSE_DIR:
                        case BYTE_CLOSE_DIR_ASYNC:
                        {
                            int fd = reader.ReadInt32();

                            if (cmd_byte == BYTE_CLOSE_DIR)
                            {
                                Log(log, name + " FSCloseDir(" + fd.ToString() + ")");
                            }
                            else
                            {
                                Log(log, name + " FSCloseDirAsync(" + fd.ToString() + ")");
                            }

                            break;
                        }

                        case BYTE_CHANGE_DIR:
                        case BYTE_CHANGE_DIR_ASYNC:
                        {
                            int    len_path = reader.ReadInt32();
                            string path     = reader.ReadString(Encoding.ASCII, len_path - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }

                            Log(log, name + " FSChangeDir(\"" + path + "\")");

                            break;
                        }

                        case BYTE_GET_CWD:
                        {
                            Log(log, name + " FSGetCwd()");

                            break;
                        }

                        case BYTE_STAT:
                        case BYTE_STAT_ASYNC:
                        {
                            int    len_path = reader.ReadInt32();
                            string path     = reader.ReadString(Encoding.ASCII, len_path - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }

                            Log(log, name + " FSGetStat(\"" + path + "\")");
                            break;
                        }

                        case BYTE_EOF:
                        {
                            int fd = reader.ReadInt32();
                            Log(log, name + " FSGetEof(" + fd.ToString() + ")");
                            break;
                        }

                        case BYTE_GETPOS:
                        {
                            int fd = reader.ReadInt32();
                            Log(log, name + " FSGetPos(" + fd.ToString() + ")");
                            break;
                        }

                        case BYTE_MOUNT_SD:
                        {
                            Log(log, name + " Trying to mount SD card");
                            break;
                        }

                        case BYTE_MOUNT_SD_OK:
                        {
                            Log(log, name + " SD card mounted !");
                            break;
                        }

                        case BYTE_MOUNT_SD_BAD:
                        {
                            Log(log, name + " Can't mount SD card");
                            break;
                        }

                        case BYTE_PING:
                        {
                            int val1 = reader.ReadInt32();
                            int val2 = reader.ReadInt32();

                            Log(log, name + " PING RECEIVED with values : " + val1.ToString() + " - " + val2.ToString());
                            break;
                        }

                        case BYTE_LOG_STR:
                        {
                            int    len_str = reader.ReadInt32();
                            string str     = reader.ReadString(Encoding.ASCII, len_str - 1);
                            if (reader.ReadByte() != 0)
                            {
                                throw new InvalidDataException();
                            }

                            Log(log, name + " LogString =>(\"" + str + "\")");
                            break;
                        }

                        default:
                            throw new InvalidDataException();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (log != null)
                {
                    Log(log, name + " " + e.Message);
                }
                else
                {
                    Console.WriteLine(name + " " + e.Message);
                }
            }
            finally
            {
                if (log != null)
                {
                    log.Close();
                }
            }
            Console.WriteLine(name + " Exit");
        }
Beispiel #59
0
 public virtual void Write(EndianBinaryWriter writer)
 {
     writer.Write((byte)CurveType);
 }
Beispiel #60
0
 internal override void WriteBody( EndianBinaryWriter writer )
 {
     writer.Write( (ushort)Data.Length );
     writer.Write( Data );
 }