Creates a stream for reading and writing variable-length data.
Notes to Callers: Make sure to include the "BitStream.resx" resource file in projects using the BitStream class.



[20051201]: Fixed problem with public virtual void Write(ulong bits, int bitIndex, int count) and public virtual int Read(out ulong bits, int bitIndex, int count) methods.



[20051127]: Added public virtual void WriteTo(Stream bits); to write the contents of the current bit stream to another stream.



[20051125]: Added the following implicit operators to allow type casting instances of the BitStream class to and from other types of Stream objects:



public static implicit operator BitStream(MemoryStream bits);

public static implicit operator MemoryStream(BitStream bits);

public static implicit operator BitStream(FileStream bits);

public static implicit operator BitStream(BufferedStream bits);

public static implicit operator BufferedStream(BitStream bits);

public static implicit operator BitStream(NetworkStream bits);

public static implicit operator BitStream(CryptoStream bits);



[20051124]: Added public virtual byte [] ToByteArray(); method.



[20051124]: The public override int ReadByte(); and public override void WriteByte(byte value) method are now supported by the BitStream class.



[20051123]: Added public BitStream(Stream bits); contructor.



Inheritance: Stream
示例#1
0
    public void TransmitStream(BKSystem.IO.BitStream data, int player)
    {
        if (m_clients[player] != null && m_clients[player].Connected)
        {
            // Pad the data by 1 bit ???
            data.Write(0);

            // Send how large the data is in the first 32 bits
            byte[] sendData   = data.ToByteArray();
            int    sendLength = IPAddress.HostToNetworkOrder(sendData.Length);
            byte[] lengthData = BitConverter.GetBytes(sendLength);

            // Choose the stream to use
            NetworkStream stream;

            stream = m_clients[player].GetStream();

            stream.Flush();

            stream.Write(lengthData, 0, lengthData.Length);
            //Debug.Log("Sending " + sendData.Length + " bytes to player " + player);

            // Then send the data
            stream.Write(sendData, 0, sendData.Length);
        }
        else
        {
            Debug.LogWarning("Attempting to transmit data while disconnected");
        }
    }
示例#2
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.SET_PLAYER_ID, 0, 16);
     packet.Write((byte)m_playerID);
     return(packet);
 }
示例#3
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)SGCommandID.SEND_DECK, 0, 16);
     packet.Write(m_deck);
     return(packet);
 }
示例#4
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)SGCommandID.PLAY_CARD_FROM_HAND, 0, 16);
     packet.Write((ushort)m_cardID, 0, 16);
     return(packet);
 }
示例#5
0
    public CGCommand ReceiveCommand()
    {
        NetworkStream stream = m_client.GetStream();

        while (stream.DataAvailable)
        {
            //Debug.Log("Data available! Reading stream...");
            // Decode the first 32 bits to find the length of the remaining data
            byte[] dataSizeBytes = new byte[4];
            stream.Read(dataSizeBytes, 0, 4);
            int dataSize = BitConverter.ToInt32(dataSizeBytes, 0);
            dataSize = IPAddress.NetworkToHostOrder(dataSize);
            //Debug.Log("Received data of size " + dataSize + " bytes");

            // Receive the data
            // Convert size to bytes
            byte[] data = new byte[dataSize];
            stream.Read(data, 0, dataSize);

            // Put the data into a BitStream
            BKSystem.IO.BitStream serverStream = new BKSystem.IO.BitStream(dataSize * 8);
            serverStream.Write(data);

            if (serverStream.Length > 0)
            {
                return(CGCommand.CreateCommandFromPacket(serverStream));
            }
        }
        return(null);
    }
示例#6
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.CAST_SPELL, 0, 16);
     packet.Write((ushort)m_cardID, 0, 16);
     packet.Write((byte)m_casterID);
     return(packet);
 }
示例#7
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.MOVE_CARD_TO_GRAVEYARD, 0, 16);
     packet.Write((byte)m_playerID);
     packet.Write((ushort)m_cardID, 0, 16);
     return(packet);
 }
示例#8
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.PHASE_TRANSITION, 0, 16);
     packet.Write(m_text.Length, 0, 8);
     packet.Write(m_text.ToCharArray(), 0, m_text.Length);
     return(packet);
 }
示例#9
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.OPPONENT_PLAY_CARD_FROM_HAND, 0, 16);
     packet.Write(m_cardData);
     packet.Write((ushort)m_cardID, 0, 16);
     packet.Write((ushort)m_channel, 0, 5);
     return(packet);
 }
示例#10
0
    public override void UnpackCommand(BKSystem.IO.BitStream packet)
    {
        int textLength;

        packet.Read(out textLength, 0, 8);
        char[] text = new char[textLength];
        packet.Read(text, 0, textLength);
        m_text = new string(text);
    }
示例#11
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.PLAYER_DRAW_CARD, 0, 16);
     packet.Write(m_cardData);
     packet.Write((ushort)m_cardID, 0, 16);
     Debug.Log("Sending card " + m_cardData.cardName + " with ID " + m_cardID);
     return(packet);
 }
示例#12
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.WAIT_FOR_CAST_SELECTION, 0, 16);
     packet.Write((ushort)m_castableCards.Count, 0, 16);
     foreach (CastableCard card in m_castableCards)
     {
         packet.Write(card);
     }
     return(packet);
 }
示例#13
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)SGCommandID.CAST_SPELL_FROM_0, 0, 16);
     packet.Write((ushort)m_cardID, 0, 16);
     packet.Write(m_targetID >= 0);
     if (m_targetID >= 0)
     {
         packet.Write((ushort)m_targetID, 0, 16);
     }
     return(packet);
 }
示例#14
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.WAIT_FOR_PLAY_FROM_HAND, 0, 16);
     packet.Write((byte)m_playerID);
     packet.Write((ushort)m_playableCards.Count, 0, 16);
     foreach (int card in m_playableCards)
     {
         packet.Write((ushort)card, 0, 16);
     }
     return(packet);
 }
示例#15
0
        public Item(byte[] itemData)
        {
            if (itemData[0] != 'J' || itemData[1] != 'M')
            {
                throw new Exception("Item data missing JM header");
            }

            bs = new BitStream(itemData);

            ReadItemData();
            ReadRemainingBits();
        }
示例#16
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.CHANNEL_SPELL, 0, 16);
     packet.Write(m_data.Count, 0, 16);
     foreach (SpellChannelData data in m_data)
     {
         packet.Write((ushort)data.cardID, 0, 16);
         packet.Write((byte)data.playerID);
         packet.Write((ushort)data.newChannel, 0, 5);
     }
     return(packet);
 }
示例#17
0
    public override void UnpackCommand(BKSystem.IO.BitStream packet)
    {
        int dataCount;

        packet.Read(out dataCount, 0, 16);
        for (int i = 0; i < dataCount; i++)
        {
            SpellChannelData data = new SpellChannelData();
            packet.Read(out data.cardID, 0, 16);
            packet.Read(out data.playerID, 0, 8);
            packet.Read(out data.newChannel, 0, 5);
            m_data.Add(data);
        }
    }
示例#18
0
    public override void UnpackCommand(BKSystem.IO.BitStream packet)
    {
        m_castableCards = new List <CastableCard>();

        int numCards;

        packet.Read(out numCards, 0, 16);
        for (int i = 0; i < numCards; i++)
        {
            CastableCard card;
            packet.Read(out card);
            m_castableCards.Add(card);
        }
    }
示例#19
0
    public override void UnpackCommand(BKSystem.IO.BitStream packet)
    {
        m_playableCards = new List <int>();
        int numCards;

        packet.Read(out m_playerID, 0, 8);
        packet.Read(out numCards, 0, 16);

        for (int i = 0; i < numCards; i++)
        {
            int cardID;
            packet.Read(out cardID, 0, 16);
            m_playableCards.Add(cardID);
        }
    }
示例#20
0
    public override void UnpackCommand(BKSystem.IO.BitStream packet)
    {
        packet.Read(out m_cardID, 0, 16);

        bool hasTarget;

        packet.Read(out hasTarget);

        if (hasTarget)
        {
            packet.Read(out m_targetID, 0, 16);
        }
        else
        {
            m_targetID = -1;
        }
    }
示例#21
0
    public static SGCommand CreateCommandFromPacket(BKSystem.IO.BitStream packet, int playerID)
    {
        if (packet.Length < 0)
        {
            return(null);
        }

        ushort commandID;

        packet.Position = 0;
        packet.Read(out commandID, 0, 16);
        Debug.Log("Read packet with server command ID: " + commandID);

        SGCommand command;

        switch (commandID)
        {
        case 1:
            command = new SGC_CastSpellFromChannel0(packet, playerID);
            break;

        case 2:
            command = new SGC_PlayCardFromHand(packet, playerID);
            break;

        case 3:
            command = new SGC_SendDeck(packet, playerID);
            break;

        case 4:
            command = new SGC_RefreshTimeout(packet, playerID);
            break;

        default:
            command = null;
            break;
        }

        command.m_ID = (SGCommandID)commandID;

        return(command);
    }
示例#22
0
    public void TransmitStream(BKSystem.IO.BitStream data)
    {
        if (m_client.Connected)
        {
            // Pad the data by 1 bit ???
            data.Write(0);

            // Send how large the data is in the first 32 bits
            byte[] sendData   = data.ToByteArray();
            int    sendLength = IPAddress.HostToNetworkOrder(sendData.Length);
            byte[] lengthData = BitConverter.GetBytes(sendLength);
            m_client.GetStream().Flush();

            m_client.GetStream().Write(lengthData, 0, lengthData.Length);
            Debug.Log("Sending " + sendData.Length + " bytes to server");

            // Then send the data
            m_client.GetStream().Write(sendData, 0, sendData.Length);
        }
    }
示例#23
0
        public Item(byte[] itemData)
        {
            if (!IsPacketData && itemData[0] != 'J' && itemData[1] != 'M')
            {
                throw new Exception("Item data missing JM header");
            }
            if(IsPacketData && itemData[0] != 0x9c && itemData[0] != 0x9d)
            {
                throw new Exception("Attempting to parse a non-item packet!");
            }

            bs = new BitStream(itemData);

            if (!IsPacketData)
            {
                // Skip 'JM' Header
                bs.SkipBits(16);
            }

            ReadItemData();
            ReadRemainingBits();
        }
示例#24
0
    public SGCommand ReceiveStream(int player)
    {
        NetworkStream stream;

        if (m_clients[player] != null && m_clients[player].Connected)
        {
            stream = m_clients[player].GetStream();
        }
        else
        {
            Debug.LogWarning("Trying to receive stream from disconnected player " + player);
            return(null);
        }

        if (stream.DataAvailable)
        {
            // Decode the first 32 bits to find the length of the remaining data
            byte[] dataSizeBytes = new byte[4];
            stream.Read(dataSizeBytes, 0, 4);
            int dataSize = BitConverter.ToInt32(dataSizeBytes, 0);
            dataSize = IPAddress.NetworkToHostOrder(dataSize);
            //Debug.Log("Received data of size " + dataSize + " bytes");

            // Receive the data
            // Convert size to bytes
            byte[] data = new byte[dataSize];
            stream.Read(data, 0, dataSize);

            // Put the data into a BitStream
            BKSystem.IO.BitStream clientStream = new BKSystem.IO.BitStream(dataSize * 8);
            clientStream.Write(data);

            if (clientStream.Length > 0)
            {
                return(SGCommand.CreateCommandFromPacket(clientStream, player));
            }
        }
        return(null);
    }
 public PayloadTelemetryValue(BitStream bs)
     : base(bs)
 {
 }
示例#26
0
 public CGC_ChannelSpell(BKSystem.IO.BitStream packet)
 {
     UnpackCommand(packet);
 }
示例#27
0
 public override void UnpackCommand(BKSystem.IO.BitStream packet)
 {
     // Nothing to unpack
 }
示例#28
0
 public CGC_OpponentDrawCard(BKSystem.IO.BitStream packet)
 {
     UnpackCommand(packet);
 }
示例#29
0
        public Telemetry(byte[] raw)
        {
            this.originalpacketlength = raw.Length;
            if (Telemetry.logHeaderLine)
            {
                Console.WriteLine("UTCTime,");
            }
            else if (this.originalpacketlength > 0)
            {
                Console.WriteLine(string.Format("{0} {1},", System.DateTime.UtcNow.ToShortDateString(), System.DateTime.UtcNow.ToLongTimeString()));
            }
            if (raw.Length == 0)
            {
                return;
            }
            BitStream bitStream = new BitStream();
            bitStream.Write(raw);
            bitStream.Position = 0L;
            this.Set(Telemetry.DataIndex.SatelliteId, new SatelliteIdTelemetryValue(this.Get2bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.FrameId, new FrameIdTelemetryValue(this.Get6bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.PanelVoltX, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PanelVoltY, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PanelVoltZ, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PanelCurrentTotal, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.BattVolt0, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.BattCurrentBus, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RebootCount, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.EpsErrorCount, new RawTelemetryValue(this.Get16bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.EpsTemp1, new RawTelemetryValue(this.Get8bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.EpsTemp2, new RawTelemetryValue(this.Get8bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.EpsTemp3, new RawTelemetryValue(this.Get8bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.BattTemp0, new RawTelemetryValue(this.Get8bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.LatchCount5_0, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.LatchCount3_3, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.ResetCause, new EPSResetcauseTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PptTrackingMode, new EPSPowerTrackingTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibSunSensorX1, new SunSensorTelemetryValue(this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibSunSensorY1, new SunSensorTelemetryValue(this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibSunSensorZ1, new SunSensorTelemetryValue(this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibPanelTempX1, new MultiplierOffsetTelemetryValue(-0.2073, 158.239, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibPanelTempX2, new MultiplierOffsetTelemetryValue(-0.2083, 159.227, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibPanelTempY1, new MultiplierOffsetTelemetryValue(-0.2076, 158.656, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibPanelTempY2, new MultiplierOffsetTelemetryValue(-0.2087, 159.045, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibBusVolt3_3, new MultiplierTelemetryValue(4.0, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibBusCurrent3_3, new MultiplierTelemetryValue(1.0, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AsibBusVolt5_0, new MultiplierTelemetryValue(6.0, this.Get10bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfReceiverDoppler, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfReceiverRSSI, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfTemp, new MultiplierOffsetTelemetryValue(-0.857, 193.672, this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfReceiveCurrent, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfTransmitCurrent3_3, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.RfTransmitCurrent5_0, new RawTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PaReversePower, new PaPowerTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PaForwardPower, new PaPowerTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PaTemperature, new PaTemperatureTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.PaCurrent, new PaCurrentTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntTempA, new AntsTemperatureTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntTempB, new AntsTemperatureTelemetryValue(this.Get8bitsAsUInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntDeploy1, new AntsDeployTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntDeploy2, new AntsDeployTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntDeploy3, new AntsDeployTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.AntDeploy4, new AntsDeployTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.SequenceNumber, new RawTelemetryValue(this.Get24bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DtmfCommandCount, new RawTelemetryValue(this.Get6bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DtmfLastCommand, new RawTelemetryValue(this.Get5bitsAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DtmfCommandSuccess, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidBob, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidEps, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidPa, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidRf, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidMse, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidAnts2, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DataValidAnts1, new DeviceDataValidTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.InEclipse, new RawTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.InSafeMode, new RawTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.HardwareABF, new BoolOnOffTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.SoftwareABF, new SoftwareAbfTelemetryValue(this.Get1bitAsInt(bitStream)));
            this.Set(Telemetry.DataIndex.DeployWait, new BoolOnOffTelemetryValue(this.Get1bitAsInt(bitStream)));
            bitStream.Position = 448L;
            BitStream bitStream2 = new BitStream(1600L);
            for (int i = 0; i < 200; i++)
            {
                bitStream2.WriteByte((byte)bitStream.ReadByte());
            }
            bitStream2.Position = 0L;
            this.Set(Telemetry.DataIndex.Payload, new PayloadTelemetryValue(bitStream2));

            if (this.originalpacketlength > 0)
            {
                Console.WriteLine(string.Empty);
            }

            if (Settings.Default.LoggingEnabled)
            {
                Telemetry.logHeaderLine = false;
            }
        }
示例#30
0
 public override void UnpackCommand(BKSystem.IO.BitStream packet)
 {
     // Nothing to unpack (in the future this could include deck restrictions)
 }
示例#31
0
        /// <summary>
        ///		Performs a bitwise <b>NOT</b> operation on the <b>bits</b> in the
        ///		current stream.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">
        ///		The current stream is closed.
        /// </exception>
        /// <remarks>
        ///		.
        /// </remarks>
        /// <returns>
        ///		A <see cref="BitStream"/> object containing the result of the bitwise
        ///		<b>NOT</b> operation on the <b>bits</b> in the current stream.
        /// </returns>
        /// <seealso cref="BitStream"/>
        public virtual BitStream Not()
        {
            if (!_blnIsOpen)
                throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed"));

            // Create the new BitStream
            var bstrmNew = new BitStream(_uiBitBuffer_Length);

            uint uiWholeUInt32Lengths = _uiBitBuffer_Length >> BitBuffer_SizeOfElement_Shift;
            uint uiCounter = 0;

            for (uiCounter = 0; uiCounter < uiWholeUInt32Lengths; uiCounter++)
                bstrmNew._auiBitBuffer[uiCounter] = ~_auiBitBuffer[uiCounter];

            // Are there any further bits in the buffer?
            if ((_uiBitBuffer_Length & BitBuffer_SizeOfElement_Mod) > 0)
            {
                uint uiBitMask = uint.MaxValue <<
                                 (int) (BitBuffer_SizeOfElement - (_uiBitBuffer_Length & BitBuffer_SizeOfElement_Mod));
                bstrmNew._auiBitBuffer[uiCounter] = ~_auiBitBuffer[uiCounter] & uiBitMask;
            }

            return bstrmNew;
        }
示例#32
0
        private static void writeCellData(byte[] cell, byte[] lastframecell, uint[] palette, BitStream cellDeltaEncoding, BitStream pixelData)
        {
            int count = 0;
            int numpixels = cell.Length;

            int delta = 0;
            byte[] pixels = new byte[16];
            for (int i = 0; i < numpixels; i++)
            {
                if (isPixelDifferent(cell[i], lastframecell[i], palette, maxBitsDifferentForPalette))
                {
                    delta |= (1 << i);
                    pixels[count] = cell[i];
                    count++;
                }
            }
            cellDeltaEncoding.Write(delta, 0, numpixels);
            bitswrittenCellDelta += numpixels;
            pixelData.Write(pixels, 0, count);
            bitswrittenCellData += count * 8;
            if (count == 0)
                emptycellswritten++;
        }
示例#33
0
 public virtual BitStream Not()
 {
     if (!this._blnIsOpen)
     {
         throw new System.ObjectDisposedException(BitStream.BitStreamResources.GetString("ObjectDisposed_BitStreamClosed"));
     }
     BitStream bitStream = new BitStream((long)((ulong)this._uiBitBuffer_Length));
     uint num = this._uiBitBuffer_Length >> 5;
     uint num2;
     for (num2 = 0u; num2 < num; num2 += 1u)
     {
         bitStream._auiBitBuffer[(int)((System.UIntPtr)num2)] = ~this._auiBitBuffer[(int)((System.UIntPtr)num2)];
     }
     if ((this._uiBitBuffer_Length & 31u) > 0u)
     {
         uint num3 = 4294967295u << (int)(32u - (this._uiBitBuffer_Length & 31u));
         bitStream._auiBitBuffer[(int)((System.UIntPtr)num2)] = (~this._auiBitBuffer[(int)((System.UIntPtr)num2)] & num3);
     }
     return bitStream;
 }
示例#34
0
        /// <summary>
        ///		Performs a bitwise e<b>X</b>clusive <b>OR</b> operation on the
        ///		<b>bits</b> in the current stream against the corresponding <b>bits</b>
        ///		in the specified stream.
        /// </summary>
        /// <exception cref="System.ObjectDisposedException">
        ///		The current stream is closed.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        ///		<i>bits</i> is a null reference (<b>Nothing</b> in Visual Basic).
        /// </exception>
        /// <exception cref="System.ArgumentException">
        ///		The stream specified by the <i>bits</i> parameter and the current
        ///		stream do not have the same number of <b>bits</b>.
        /// </exception>
        /// <remarks>
        ///		.
        /// </remarks>
        /// <param name="bits">
        ///		A <see cref="BitStream"/> object with which to perform the bitwise
        ///		e<b>X</b>clusive <b>OR</b> operation.
        /// </param>
        /// <returns>
        ///		A <see cref="BitStream"/> object containing the result of the bitwise
        ///		e<b>X</b>clusive <b>OR</b> operation on the <b>bits</b> in the current
        ///		stream against the corresponding <b>bits</b> in the specified stream.
        /// </returns>
        /// <seealso cref="BitStream"/>
        public virtual BitStream Xor(BitStream bits)
        {
            if (!_blnIsOpen)
                throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed"));
            if (bits == null)
                throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream"));
            if (bits.Length != _uiBitBuffer_Length)
                throw new ArgumentException(BitStreamResources.GetString("Argument_DifferentBitStreamLengths"));

            // Create the new BitStream
            BitStream bstrmNew = new BitStream(_uiBitBuffer_Length);

            uint uiWholeUInt32Lengths = _uiBitBuffer_Length >> BitBuffer_SizeOfElement_Shift;
            uint uiCounter = 0;

            for (uiCounter = 0; uiCounter < uiWholeUInt32Lengths; uiCounter++)
                bstrmNew._auiBitBuffer[uiCounter] = _auiBitBuffer[uiCounter] ^ bits._auiBitBuffer[uiCounter];

            // Are there any further bits in the buffer?
            if ((_uiBitBuffer_Length & BitBuffer_SizeOfElement_Mod) > 0)
            {
                uint uiBitMask = uint.MaxValue << (int)(BitBuffer_SizeOfElement - (_uiBitBuffer_Length & BitBuffer_SizeOfElement_Mod));
                bstrmNew._auiBitBuffer[uiCounter] = _auiBitBuffer[uiCounter] ^ bits._auiBitBuffer[uiCounter] & uiBitMask;
            }

            return bstrmNew;
        }
示例#35
0
        /// <summary>
        /// Writes an item property to the BitStream
        /// </summary>
        /// <param name="bs">Bitstream to write property to</param>
        /// <param name="property">Property to write</param>
        private void WriteItemProperty(BitStream bs, PropertyInfo property)
        {
            if (property.ID == 0x1ff)
            {
                bs.WriteReversed(property.ID, 9);
                return;
            }

            ItemStatCost statCost = ItemDefs.ItemStatCostsById[property.ID];

            int fixedValue = property.Value + statCost.SaveAdd;

            if (!property.IsAdditionalProperty)
            {
                bs.WriteReversed(property.ID, 9);
            }

            bs.WriteReversed(fixedValue, statCost.SaveBits);

            if (statCost.SaveParamBits > 0)
            {
                bs.WriteReversed(property.ParamValue, statCost.SaveParamBits);
            }
        }
示例#36
0
        private static byte[] buildFrame(int width, int height, BitStream cellMatrix, BitStream cellDeltaEncoding, BitStream pixelData)
        {
            int cellWidth = width / 4 + ((width % 4 != 0) ? 1 : 0);
            int cellHeight = height / 4 + ((height % 4 != 0) ? 1 : 0);
            byte[] frame = new byte[width * height];

            uint[] matrix = cellMatrix.GetBuffer();
            uint[] delta = cellDeltaEncoding.GetBuffer();
            uint[] pixels = pixelData.GetBuffer();

            byte[] matrix2 = byteArrayFromUintArray(matrix);
            byte[] delta2 = byteArrayFromUintArray(delta);
            byte[] pixels2 = byteArrayFromUintArray(pixels);
            byte[] totaldata = new byte[matrix2.Length + delta2.Length + pixels2.Length];
            Array.Copy(matrix2, 0, totaldata, 0, matrix2.Length);
            Array.Copy(delta2, 0, totaldata, matrix2.Length, delta2.Length);
            Array.Copy(pixels2, 0, totaldata, matrix2.Length + delta2.Length, pixels2.Length);

            byte[] compressed = new byte[0x1000000];
            int compLength = 0x1000000;
            UltimaXNA.Network.Compression.Pack(compressed, ref compLength, totaldata, totaldata.Length);

            int matrixIndex = 0, matrixOffset = 0;
            int deltaIndex = 0, deltaOffset = 0;
            int pixelsIndex = 0, pixelsOffset = 0;

            int cellIndex = 0;
            bool inEmptyCellSpan = true;
            bool frameComplete = false;
            while (!frameComplete)
            {
                int matrixCode = valueFromBitStream(matrix, ref matrixIndex, ref matrixOffset, 4);
                if (inEmptyCellSpan)
                {
                    cellIndex += matrixCode;
                    inEmptyCellSpan = false;
                }
                else
                {
                    for (int i = 0; i < matrixCode; i++)
                    {
                        int cellX = (cellIndex % cellWidth) * 4;
                        int cellY = (cellIndex / cellWidth) * 4;
                        int cellW = ((width - cellX) >= 4) ? 4 : width - cellX;
                        int cellH = ((height - cellY) >= 4) ? 4 : height - cellY;
                        int deltaCode = valueFromBitStream(delta, ref deltaIndex, ref deltaOffset, cellW * cellH);
                        for (int j = 0; j < cellW * cellH; j++)
                        {
                            if ((deltaCode & deltaBits[j]) != 0)
                            {
                                frame[cellX + (j % cellW) + ((cellY + (j / cellW)) * width)] = (byte)valueFromBitStream(pixels, ref pixelsIndex, ref pixelsOffset, 8);
                            }
                        }
                        cellIndex++;
                    }
                    inEmptyCellSpan = true;
                }
                if (cellIndex == cellWidth * cellHeight)
                    frameComplete = true;
            }

            return frame;
        }
示例#37
0
        /// <summary>
        /// Converts all stat data into raw data for save file
        /// </summary>
        /// <returns>Raw stat data ready for insertion into save file</returns>
        public byte[] GetStatBytes()
        {
            BitStream bits = new BitStream();

            bits.WriteReversed('g', 8);
            bits.WriteReversed('f', 8);

            var sortedValues = from n in statValues where true orderby n.Key select n;

            foreach (var stat in sortedValues)
            {
                bits.WriteReversed(stat.Key, 9);

                int valShift = 0;
                int bitCount = ItemDefs.ItemStatCostsById[stat.Key].CSvBits;

                if (ItemDefs.ItemStatCostsById.ContainsKey(stat.Key))
                {
                    valShift = ItemDefs.ItemStatCostsById[stat.Key].ValShift;
                }

                bits.WriteReversed((uint)((stat.Value << valShift)), bitCount);
            }

            // Write termining stat index
            bits.WriteReversed(0x1ff, 9);

            // Add 0 padding to align to byte, if needed
            int remainingBitsForAlignment = 8 - (int)(bits.Position % 8);
            if (remainingBitsForAlignment > 0)
            {
                bits.WriteReversed(0, remainingBitsForAlignment);
            }

            return bits.ToReversedByteArray();
        }
示例#38
0
 private NetOutgoingMessage CreateAtmosUpdatePacket(BitStream records)
 {
     byte[] recs = Compress(records);
     if (recs == null)
         return null;
     NetOutgoingMessage msg = IoCManager.Resolve<ISS13NetServer>().CreateMessage();
     msg.Write((byte) NetMessage.AtmosDisplayUpdate);
     msg.Write((int) records.Length);
     msg.Write(recs.Length);
     msg.Write(recs);
     return msg;
 }
示例#39
0
 private uint Get16bitsAsUInt(BitStream bs)
 {
     uint result;
     bs.Read(out result, 0, 16);
     return result;
 }
示例#40
0
 private void SendAtmosUpdatePacket(BitStream records)
 {
     NetOutgoingMessage msg = CreateAtmosUpdatePacket(records);
     if (msg == null)
         return;
     IoCManager.Resolve<ISS13NetServer>().SendToAll(msg, NetDeliveryMethod.Unreliable);
 }
示例#41
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.REQUEST_DECK, 0, 16);
     return(packet);
 }
示例#42
0
        public void SendAtmosStateTo(NetConnection client)
        {
            var m = IoCManager.Resolve<IMapManager>();

            int numberOfGasTypes = Enum.GetValues(typeof (GasType)).Length;
            var records = new BitStream(m.GetMapHeight()*m.GetMapWidth()*numberOfGasTypes);
            int displayBitsWritten = 0;

            for (int x = 0; x < m.GetMapWidth(); x++)
            {
                for (int y = 0; y < m.GetMapHeight(); y++)
                {
                    Tile t = (Tile)m.GetFloorAt(new Vector2(x * m.GetTileSpacing(), y * m.GetTileSpacing()));
                    if (t == null)
                        continue;
                    displayBitsWritten = t.GasCell.PackDisplayBytes(records, true);
                }
            }
            NetOutgoingMessage msg = CreateAtmosUpdatePacket(records);
            if (msg == null)
                return;
            IoCManager.Resolve<ISS13NetServer>().SendMessage(msg, client, NetDeliveryMethod.ReliableUnordered);
        }
示例#43
0
 public SGC_CastSpellFromChannel0(BKSystem.IO.BitStream packet, int playerID)
 {
     m_playerID = playerID;
     UnpackCommand(packet);
     Debug.Log("Created SGC_CastSpellFromChannel0 with cardID " + m_cardID + ".");
 }
示例#44
0
        private static void transform(BinaryReader bin)
        {
            FrameXNA[] frames = AnimationsXNA.GetAnimation(bin);

            BitStream CellMatrixStream = new BitStream();
            BitStream CellDeltaEncodingStream = new BitStream();
            BitStream CellDataStream = new BitStream();

            int width, height, xoffset, yoffset;
            getWidthHeight(frames, out width, out height, out xoffset, out yoffset);

            uint[][] pixeldata = new uint[frames.Length][];
            for (int i = 0; i < frames.Length; i++)
                pixeldata[i] = getPixelData(frames[i], width, height,
                    xoffset - frames[i].Center.X,
                    (height + (yoffset - frames[i].Center.Y)) - frames[i].Texture.Height);

            uint[] palette = new uint[0x100];
            uint[] palettesortvalues = new uint[0x100];
            uint[] paletteSimilars = new uint[0x100];
            for (int i = 0; i < frames.Length; i++)
                getPalette(pixeldata[i], palette, palettesortvalues);
            palettesortvalues[0] = int.MaxValue;
            sortPalette(palette, palettesortvalues);
            // findSimilarShadesInPalette(palette, ref paletteSimilars);
            // combinePalette(palette, paletteSimilars, palettesortvalues);
            // sortPalette(palette, palettesortvalues, paletteSimilars);

            // debug = count num of pixels using top 16 colors.
            int topsixteen = 0; int others = 0;
            for (int i = 1; i < 17; i++)
                topsixteen += (int)palettesortvalues[i];
            for (int i = 17; i < 256; i++)
                others += (int)palettesortvalues[i];

            byte[][] framedata = new byte[frames.Length][];
            for (int i = 0; i < frames.Length; i++)
                framedata[i] = palettedFrame(pixeldata[i], palette, paletteSimilars);

            for (int i = 0; i < frames.Length; i++)
            {
                byte[][] framecells = getCells(framedata[i], width);
                byte[][] lastFrameCells;
                if (i > 0)
                    lastFrameCells = getCells(buildFrame(width, height, CellMatrixStream, CellDeltaEncodingStream, CellDataStream), width);
                else
                    lastFrameCells = new byte[0][];
                getStreams(framecells, lastFrameCells, i, width, palette, CellMatrixStream, CellDeltaEncodingStream, CellDataStream);
                byte[] newframedata = buildFrame(width, height, CellMatrixStream, CellDeltaEncodingStream, CellDataStream);
                FrameXNA frame = new FrameXNA(AnimationsXNA.DEBUG_GFX, palette, newframedata, width, height, 0, 0);
                frame.Texture.Save("test.bmp", Microsoft.Xna.Framework.Graphics.ImageFileFormat.Bmp);
            }
            int size =
                (int)(CellMatrixStream.Length >> 3) +
                (int)(CellDeltaEncodingStream.Length >> 3) +
                (int)(CellDataStream.Length >> 3);
        }
示例#45
0
        /// <summary>
        /// Function to pack an array of one-byte representations of a given gas's visibility.
        /// </summary>
        /// <param name="all">send em all anyway?</param>
        /// <returns></returns>
        /// 
        public int PackDisplayBytes(BitStream bits, bool all = false)
        {
            int changedTypes = 0;

            //How many gas types we have!
            int typesCount = Enum.GetValues(typeof (GasType)).Length;
            var gasChanges = new byte[typesCount];
            int bitCount = typesCount;
            for (int i = typesCount - 1; i >= 0; i--)
            {
                byte amount;
                var t = (GasType) i;
                switch (t)
                {
                    case GasType.Toxin:
                        if (gasMixture.gasses[(int)GasType.Toxin] > 0.00005f && (checkUpdateThreshold(GasType.Toxin) || all))
                        {
                            amount = (byte)normalizeGasAmount(gasMixture.gasses[(int)GasType.Toxin]);
                            gasChanges[i] = amount;
                            changedTypes = (changedTypes | (1 << i));
                            lastSentGasses[GasType.Toxin] = gasMixture.gasses[(int)GasType.Toxin];
                            bitCount += 4;
                        }
                        else
                        {
                            lastSentGasses[GasType.Toxin] = 0;
                        }
                        break;
                    case GasType.WVapor:
                        //if (gasMixture.gasses[GasType.WVapor] > 0.005f && (checkUpdateThreshold(GasType.WVapor) || all))
                        if (gasMixture.Burning)
                        {
                            amount = 15; // normalizeGasAmount(gasMixture.gasses[GasType.WVapor]);
                            gasChanges[i] = amount;
                            changedTypes = (changedTypes | (1 << i));
                            lastSentGasses[GasType.WVapor] = gasMixture.gasses[(int)GasType.WVapor];
                            bitCount += 4;
                        }
                        else
                        {
                            amount = 0; // normalizeGasAmount(gasMixture.gasses[GasType.WVapor]);
                            gasChanges[i] = amount;
                            changedTypes = (changedTypes | (1 << i));
                            lastSentGasses[GasType.WVapor] = gasMixture.gasses[(int)GasType.WVapor];
                            bitCount += 4;
                            //lastSentGasses[GasType.WVapor] = 0;
                        }
                        break;
                    default:
                        break;
                }
            }

            //Make a new bitstream with the number o bits we need.
            bits.Write(changedTypes, 0, typesCount); //write 8 bits for what gas types have changed...
            for (int i = typesCount - 1; i >= 0; i--)
            {
                int type = 1 << i;
                //Checks flags in the form of 00001011 -- each 1 is a gas type that needs sending... I know this is nuts but it works great!
                if ((changedTypes & type) == type)
                {
                    bits.Write(gasChanges[i], 0, 4);
                }
            }

            return bitCount;
        }
示例#46
0
        private static void getStreams(byte[][] celldata, byte[][] lastCellData, int frame, int width, uint[] palette, BitStream cellMatrix, BitStream cellDeltaEncoding, BitStream pixelData)
        {
            bool newLine = true;
            int x = 0;
            bool emptyCellSpan = true;
            byte cellSpanLength = 0;
            int cellMatrixEntryMaxSizeBits = 4;
            int cellMatrixEntryMaxSize = (int)Math.Pow(2, cellMatrixEntryMaxSizeBits) - 1;
            byte[] emptyCell = new byte[16];

            for (int i = 0; i < celldata.Length; i++)
            {
                if (newLine)
                {
                    newLine = false;
                    x = 0;
                }

                bool writeCell;
                if (frame == 0)
                    writeCell = !isCellEmpty(celldata[i]);
                else
                    writeCell = isCellDifferent(celldata[i], lastCellData[i], palette);

                if (writeCell)
                {
                    if (!emptyCellSpan)
                    {
                        cellSpanLength++;
                        if (cellSpanLength == cellMatrixEntryMaxSize)
                        {
                            cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                            cellSpanLength = 0;
                            cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                            bitswrittenCellMatrix += 8;
                        }
                    }
                    else
                    {
                        cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                        bitswrittenCellMatrix += 4;
                        cellSpanLength = 1;
                        emptyCellSpan = false;
                    }
                    byte[] lastframecell = (frame == 0) ? emptyCell : lastCellData[i];
                    writeCellData(celldata[i], lastframecell, palette, cellDeltaEncoding, pixelData);
                    cellswritten++;
                }
                else
                {
                    if (emptyCellSpan)
                    {
                        cellSpanLength++;
                        if (cellSpanLength == cellMatrixEntryMaxSize)
                        {
                            cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                            cellSpanLength = 0;
                            cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                            bitswrittenCellMatrix += 8;
                        }
                    }
                    else
                    {
                        cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
                        bitswrittenCellMatrix += 4;
                        cellSpanLength = 1;
                        emptyCellSpan = true;
                    }
                }

                x += 4;
                if (x >= width)
                    newLine = true;
            }

            if (cellSpanLength > 0)
            {
                cellMatrix.Write(cellSpanLength, 0, cellMatrixEntryMaxSizeBits);
            }
        }
示例#47
0
 public override BKSystem.IO.BitStream PackCommand()
 {
     BKSystem.IO.BitStream packet = new BKSystem.IO.BitStream();
     packet.Write((ushort)CGCommandID.OPPONENT_DRAW_CARD, 0, 16);
     return(packet);
 }
示例#48
0
 private byte Get8bitsAsUInt(BitStream bs)
 {
     byte result;
     bs.Read(out result, 0, 8);
     return result;
 }
示例#49
0
 public static string GetFitterMessage(BitStream raw)
 {
     string msg = System.Text.Encoding.ASCII.GetString(raw.ToByteArray());
       msg = msg.Replace("\0", "");
       return msg;
 }
示例#50
0
 private int Get6bitsAsInt(BitStream bs)
 {
     int result;
     bs.Read(out result, 0, 6);
     return result;
 }
示例#51
0
        public void HandleAtmosDisplayUpdate(NetIncomingMessage message)
        {
            if (!_loaded)
                return;
            //Length of records in bits
            int lengthBits = message.ReadInt32();
            int lengthBytes = message.ReadInt32();
            var records = new byte[lengthBytes];
            message.ReadBytes(records, 0, lengthBytes);
            byte[] decompressed = Decompress(records);
            var recordStream = new BitStream(lengthBits);
            int bitsWritten = 0;
            for (int i = 0; i < decompressed.Length; i++)
            {
                int toWrite = 8;
                if (toWrite > lengthBits - bitsWritten)
                    toWrite = lengthBits - bitsWritten;
                recordStream.Write(decompressed[i], 0, toWrite);
                bitsWritten += toWrite;
            }

            int typesCount = Enum.GetValues(typeof (GasType)).Length;
            recordStream.Position = 0;
            int types = 0;
            byte amount = 0;
            for (int x = 0; x < _mapWidth; x++)
            {
                for (int y = 0; y < _mapHeight; y++)
                {
                    recordStream.Read(out types, 0, typesCount);

                    for (int i = typesCount - 1; i >= 0; i--)
                    {
                        if ((types & (1 << i)) == (1 << i))
                        {
                            recordStream.Read(out amount, 0, 4);
                            Tile t = (Tile)GetFloorAt(new Vector2D(x * TileSpacing, y * TileSpacing));
                            if (t == null)
                                continue;
                            t.SetAtmosDisplay((GasType) i, amount);
                        }
                    }
                }
            }

            var gameScreen = IoCManager.Resolve<IStateManager>().CurrentState as GameScreen;
            gameScreen.RecalculateScene();
        }
示例#52
0
 private int Get1bitAsInt(BitStream bs)
 {
     int result;
     bs.Read(out result, 0, 1);
     return result;
 }
示例#53
0
        /// <summary>
        ///		Creates a copy of the current stream.
        /// </summary>
        /// <remarks>
        ///		This method works even when the current stream is closed.
        /// </remarks>
        /// <returns>
        ///		A <see cref="BitStream"/> object representing the copy of the current
        ///		stream.
        /// </returns>
        /// <seealso cref="BitStream"/>
        public virtual BitStream Copy()
        {
            BitStream bstrmCopy = new BitStream(this.Length);

            Buffer.BlockCopy(_auiBitBuffer, 0, bstrmCopy._auiBitBuffer, 0, bstrmCopy._auiBitBuffer.Length << 2);

            bstrmCopy._uiBitBuffer_Length = this._uiBitBuffer_Length;

            return bstrmCopy;
        }
示例#54
0
        /// <summary>
        /// Parses raw character stat data
        /// </summary>
        /// <param name="headerBytes">Raw characte stat data found between "gf" and "if" near offset 765 in save file</param>
        /// <remarks>Bit lengths of stat types are found in the CSvBits column of ItemStatCost.txt</remarks>
        /// Source: http://phrozenkeep.hugelaser.com/forum/viewtopic.php?f=8&t=9011&start=50
        private void ReadStats()
        {
            BitStream bs = new BitStream(statsBytes);

            // Skip header bytes
            bs.SkipBits(8);
            bs.SkipBits(8);

            while (bs.RemainingBits >= 9)
            {
                // ID of stat (See ItemStatCost.txt)
                int statIndex = (int)bs.ReadReversed(9);
                // Value contains this many bits (See CSvBits in ItemStatCost.txt)
                int statValueBits = 0;
                // Value needs to be shifted by this amount
                int valShift = 0;

                // Terminating stat index
                if (statIndex == 0x1ff)
                {
                    break;
                }

                statValueBits = ItemDefs.ItemStatCostsById[statIndex].CSvBits;
                if (statValueBits == 0)
                {
                    break;
                }

                valShift = ItemDefs.ItemStatCostsById[(int)statIndex].ValShift;

                int statValue = (int)bs.ReadReversed(statValueBits);
                if (!statValues.ContainsKey(statIndex))
                {
                    statValues.Add(statIndex, (statValue >> valShift));
                }
            }
        }
示例#55
0
 public abstract void UnpackCommand(BKSystem.IO.BitStream packet);
示例#56
0
        /// <summary>
        /// Converts specified item into item format for save file
        /// </summary>
        /// <returns>Byte representation of item for save file</returns>
        public byte[] GetItemBytes()
        {
            BitStream bs = new BitStream();

            bs.WriteReversed('J', 8);
            bs.WriteReversed('M', 8);

            var ordered = dataEntries.OrderBy(n => n.Value.Index);

            foreach (var item in ordered)
            {
                if (item.Value.Value is string)
                {
                    string value = item.Value.Value as string;

                    if (item.Key == "ItemCode")
                    {
                        foreach (var ch in value)
                        {
                            bs.WriteReversed(ch, 8);
                        }
                        bs.WriteReversed(' ', 8);
                    }
                    else if (item.Key == "EarName" || item.Key == "PersonalizedName")
                    {
                        foreach (var ch in value)
                        {
                            bs.WriteReversed(ch, 7);
                        }
                        bs.WriteReversed(0, 7);
                    }
                    else
                    {
                        throw new Exception("Unknown string type in item data");
                    }
                }
                else if (item.Value.Value is ValueType)
                {
                    // LAST key is the very last property added to the item data
                    if (item.Key == "LAST")
                        continue;

                    TypeCode valueType = Type.GetTypeCode(item.Value.Value.GetType());

                    if (valueType == TypeCode.UInt32)
                    {
                        uint value = (uint)item.Value.Value;

                        if (item.Key == "Defense")
                        {
                            value += (uint)ItemDefs.ItemStatCostsByName["armorclass"].SaveAdd;
                        }
                        else if (item.Key == "MaxDurability")
                        {
                            value += (uint)ItemDefs.ItemStatCostsByName["maxdurability"].SaveAdd;
                        }
                        else if (item.Key == "Durability")
                        {
                            value += (uint)ItemDefs.ItemStatCostsByName["durability"].SaveAdd;
                        }

                        bs.WriteReversed(value, item.Value.BitCount);
                    }
                    else if (valueType == TypeCode.Int32)
                    {
                        bs.WriteReversed((uint)((int)item.Value.Value), item.Value.BitCount);
                    }
                    else if (valueType == TypeCode.Boolean)
                    {
                        bs.Write((bool)item.Value.Value);
                    }
                    else
                    {
                        throw new Exception("Invalid ValueType!");
                    }
                }
                else
                {
                    throw new Exception("Invalid data type in item dataEntries");
                }
            }

            foreach (var item in properties)
            {
                WriteItemProperty(bs, item);
            }

            foreach (var item in propertiesSet)
            {
                WriteItemProperty(bs, item);
            }

            foreach (var item in propertiesRuneword)
            {
                WriteItemProperty(bs, item);
            }

            // Some simple items do have remaining data such as the soulstone
            if (IsSimpleItem)
            {
                //TODO: Enable renaming of ear and personlized names?
                if (remainingBytes != null)
                {
                    bs.WriteReversed(remainingBytes);
                }

                if (dataEntries.ContainsKey("LAST"))
                {
                    var lastEntry = dataEntries["LAST"];
                    bs.WriteReversed((uint)lastEntry.Value, lastEntry.BitCount);
                }
            }
            else
            {
                // Fill the last byte with 0 if it's not already full
                if ((bs.Position % 8) != 0)
                {
                    int bitsToAdd = 8 - (int)(bs.Position % 8);
                    if (bitsToAdd > 0)
                    {
                        bs.WriteReversed(0, bitsToAdd);
                    }
                }
            }

            return bs.ToReversedByteArray();
        }
示例#57
0
 public virtual BitStream Copy()
 {
     BitStream bitStream = new BitStream(this.Length);
     System.Buffer.BlockCopy(this._auiBitBuffer, 0, bitStream._auiBitBuffer, 0, bitStream._auiBitBuffer.Length << 2);
     bitStream._uiBitBuffer_Length = this._uiBitBuffer_Length;
     return bitStream;
 }
示例#58
0
        private void CheckNetworkUpdate()
        {
            var m = IoCManager.Resolve<IMapManager>();

            if ((DateTime.Now - lastAtmosDisplayPush).TotalMilliseconds > 1000)
            {
                bool sendUpdate = false;
                int numberOfGasTypes = Enum.GetValues(typeof (GasType)).Length;
                var records = new BitStream(m.GetMapHeight()*m.GetMapWidth()*numberOfGasTypes);
                for (int x = 0; x < m.GetMapWidth(); x++)
                {
                    for (int y = 0; y < m.GetMapHeight(); y++)
                    {
                        Tile t = (Tile)m.GetFloorAt(new Vector2(x * m.GetTileSpacing(), y * m.GetTileSpacing()));
                        if (t == null)
                            continue;
                        int displayBitsWritten = t.GasCell.PackDisplayBytes(records);
                        if (displayBitsWritten > numberOfGasTypes)
                            sendUpdate = true;
                    }
                }
                if (sendUpdate)
                {
                    SendAtmosUpdatePacket(records);
                }
                lastAtmosDisplayPush = DateTime.Now;
            }
        }
示例#59
0
 public virtual BitStream Or(BitStream bits)
 {
     if (!this._blnIsOpen)
     {
         throw new System.ObjectDisposedException(BitStream.BitStreamResources.GetString("ObjectDisposed_BitStreamClosed"));
     }
     if (bits == null)
     {
         throw new System.ArgumentNullException("bits", BitStream.BitStreamResources.GetString("ArgumentNull_BitStream"));
     }
     if (bits.Length != (long)((ulong)this._uiBitBuffer_Length))
     {
         throw new System.ArgumentException(BitStream.BitStreamResources.GetString("Argument_DifferentBitStreamLengths"));
     }
     BitStream bitStream = new BitStream((long)((ulong)this._uiBitBuffer_Length));
     uint num = this._uiBitBuffer_Length >> 5;
     uint num2;
     for (num2 = 0u; num2 < num; num2 += 1u)
     {
         bitStream._auiBitBuffer[(int)((System.UIntPtr)num2)] = (this._auiBitBuffer[(int)((System.UIntPtr)num2)] | bits._auiBitBuffer[(int)((System.UIntPtr)num2)]);
     }
     if ((this._uiBitBuffer_Length & 31u) > 0u)
     {
         uint num3 = 4294967295u << (int)(32u - (this._uiBitBuffer_Length & 31u));
         bitStream._auiBitBuffer[(int)((System.UIntPtr)num2)] = (this._auiBitBuffer[(int)((System.UIntPtr)num2)] | (bits._auiBitBuffer[(int)((System.UIntPtr)num2)] & num3));
     }
     return bitStream;
 }
示例#60
0
        private byte[] Compress(BitStream rawStream)
        {
            rawStream.Position = 0;
            var raw = new byte[rawStream.Length8];
            for (int i = 0; i < rawStream.Length8; i++)
            {
                rawStream.Read(out raw[i]);
            }
            var byteLength = (int) rawStream.Length8;
            if (byteLength == 0)
            {
                return null;
            }

            using (var memory = new MemoryStream())
            {
                using (var gzip = new GZipStream(memory, CompressionMode.Compress, true))
                {
                    gzip.Write(raw, 0, raw.Length);
                }
                return memory.ToArray();
            }
        }