System.Collections.Generic.List.Add(ushort)

Here are the examples of the csharp api System.Collections.Generic.List.Add(ushort) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

287 Examples 7

19 Source : Table.cs
with GNU General Public License v3.0
from laszlodaniel

public List<ushort> selectRecordsReturnIDs( byte field, long key, bool sorted = false )
		{
			List<ushort> ret = new List<ushort>();
			long val;
			for( ushort i = 0; i < this.rowCount; ++i )
			{
				val = this.readField( this.records[i], field );
				if( val == key )
				{
					ret.Add( i );
				}
				else if( sorted && ( val > key ) )
				{
					break;
				}
			}
			return ret;
		}

19 Source : CCDDiagnosticsTable.cs
with GNU General Public License v3.0
from laszlodaniel

public void AddRow(ushort modifiedID, string row)
        {
            int location = 0;

            if (!IDByteList.Contains(modifiedID) && ((modifiedID >> 8) != 0xB2) && ((modifiedID >> 8) != 0xF2))
            {
                byte uniqueID = (byte)((modifiedID >> 8) & 0xFF);
                if (!UniqueIDByteList.Contains(uniqueID)) UniqueIDByteList.Add(uniqueID);

                IDByteList.Add(modifiedID);
                IDByteList.Sort();
                location = IDByteList.FindIndex(x => x == modifiedID);

                if (IDByteList.Count == 1)
                {
                    Table.RemoveAt(listStart);
                    Table.Insert(listStart, row);
                }
                else
                {
                    Table.Insert(listStart + location, row);
                }

                lastUpdatedLine = listStart + location;
            }
            else if (IDByteList.Contains(modifiedID) && ((modifiedID >> 8) != 0xB2) && ((modifiedID >>8) != 0xF2)) // if it's not diagnostic request or response message
            {
                location = IDByteList.FindIndex(x => x == modifiedID);
                Table.RemoveAt(listStart + location);
                Table.Insert(listStart + location, row);
                lastUpdatedLine = listStart + location;
            }

            switch (modifiedID >> 8)
            {
                case 0xB2:
                    if (!B2F2IDByteList.Contains(0xB2)) B2F2IDByteList.Add(0xB2);
                    B2F2IDByteList.Sort();
                    Table.RemoveAt(B2Row);
                    Table.Insert(B2Row, row);
                    //Table.RemoveAt(F2Row);
                    //Table.Insert(F2Row, "│ F2 -- -- -- -- --       │ RESPONSE |                                          │                         │             │");
                    lastUpdatedLine = B2Row;
                    break;
                case 0xF2:
                    if (!B2F2IDByteList.Contains(0xF2)) B2F2IDByteList.Add(0xF2);
                    B2F2IDByteList.Sort();
                    Table.RemoveAt(F2Row);
                    Table.Insert(F2Row, row);
                    lastUpdatedLine = F2Row;
                    break;
                default:
                    break;
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from laszlodaniel

private void SerialDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            int DataLength = sp.BytesToRead;

            // This approach enables reading multiple broken transmissions
            // First just add the received bytes to a global list
            for (int i = 0; i < DataLength; i++)
            {
                try
                {
                    bufferlist.Add((byte)sp.ReadByte());
                }
                catch
                {
                    Util.UpdateTextBox(CommunicationTextBox, "[INFO] Serial read error", null);
                    break;
                }
            }

            // Multiple packets are handled one after another in this while-loop
            while (bufferlist.Count > 0)
            {
                if (bufferlist[0] == 0x3D)
                {
                    if (bufferlist.Count < 3) break; // wait for the length bytes

                    int PacketLength = (bufferlist[1] << 8) + bufferlist[2];
                    int FullPacketLength = PacketLength + 4;

                    if (bufferlist.Count < FullPacketLength) break; // wait for the rest of the bytes to arrive

                    byte[] Packet = new byte[FullPacketLength];
                    int PayloadLength = PacketLength - 2;
                    byte[] Payload = new byte[PayloadLength];
                    int ChecksumLocation = PacketLength + 3;
                    byte DataCode = 0;
                    byte Source = 0;
                    byte Command = 0;
                    byte SubDataCode = 0;
                    byte Checksum = 0;
                    byte CalculatedChecksum = 0;

                    Array.Copy(bufferlist.ToArray(), 0, Packet, 0, Packet.Length);

                    Checksum = Packet[ChecksumLocation]; // get packet checksum byte

                    for (int i = 1; i < ChecksumLocation; i++)
                    {
                        CalculatedChecksum += Packet[i]; // calculate checksum
                    }

                    if (CalculatedChecksum == Checksum) // verify checksum
                    {
                        DataCode = Packet[3];
                        Source = (byte)((DataCode >> 7) & 0x01);
                        Command = (byte)(DataCode & 0x0F);
                        SubDataCode = Packet[4];

                        if (PayloadLength > 0) // copy payload bytes if available
                        {
                            Array.Copy(Packet, 5, Payload, 0, PayloadLength);
                        }

                        if (Source == 1) // highest bit set in the DataCode byte means the packet is coming from the device
                        {
                            switch (Command) // based on the datacode decide what to do with this packet
                            {
                                case 0x00: // reset
                                    switch (SubDataCode)
                                    {
                                        case 0x00:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Device is resetting, please wait...", Packet);
                                            break;
                                        case 0x01:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Device is ready", Packet);
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Unknown reset packet", Packet);
                                            break;
                                    }
                                    break;
                                case 0x01: // handshake
                                    Util.UpdateTextBox(CommunicationTextBox, "[RX->] Handshake received", Packet);
                                    if (Encoding.ASCII.GetString(Payload, 0, Payload.Length) == "SBHACK") Util.UpdateTextBox(CommunicationTextBox, "[INFO] Handshake OK: SBHACK", null);
                                    else Util.UpdateTextBox(CommunicationTextBox, "[INFO] Handshake ERROR: " + Encoding.ASCII.GetString(Payload, 0, Payload.Length), null);
                                    break;
                                case 0x02: // status
                                    switch (SubDataCode)
                                    {
                                        case 0x01: // timestamp
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Timestamp received", Packet);
                                            if (Payload.Length > 3)
                                            {
                                                TimeSpan ElapsedTime = TimeSpan.FromMilliseconds(Payload[0] << 24 | Payload[1] << 16 | Payload[2] << 8 | Payload[3]);
                                                DateTime Timestamp = DateTime.Today.Add(ElapsedTime);
                                                string TimestampString = Timestamp.ToString("HH:mm:ss.fff");
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Timestamp: " + TimestampString, null);
                                            }
                                            break;
                                        case 0x02: // scan SMBus address result
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Scan SMBus address result", Packet);
                                            if ((Payload.Length > 0) && (Payload[0] != 0xFF))
                                            {
                                                string SmartBatteryAddressList = Util.ByteToHexString(Payload, 0, Payload.Length);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] SMBus device(s): " + SmartBatteryAddressList, null);

                                                SMBusAddressComboBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    SMBusAddressComboBox.Items.Clear();
                                                    for (int i = 0; i < Payload.Length; i++)
                                                    {
                                                        SMBusAddressComboBox.Items.Add(Util.ByteToHexString(Payload, i, i + 1));
                                                    }
                                                    SMBusAddressComboBox.SelectedIndex = 0;
                                                    SMBusAddressSelectButton.Enabled = true;
                                                });
                                            }
                                            else
                                            {
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] No SMBus device found", null);

                                                SMBusAddressComboBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    SMBusAddressComboBox.Items.Clear();
                                                    SMBusAddressComboBox.Items.Add("--");
                                                    SMBusAddressSelectButton.Enabled = false;
                                                });
                                            }
                                            break;
                                        case 0x03: // smbus register dump
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] SMBus register dump (" + Util.ByteToHexString(Payload, 0, 1) + "-" + Util.ByteToHexString(Payload, 1, 2) + ")", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                SMBusRegisterDumpList.Clear();

                                                for (int i = 1; i < (Payload.Length - 2); i++)
                                                {
                                                    i += 2;
                                                    SMBusRegisterDumpList.Add((ushort)((Payload[i] << 8) + Payload[i + 1]));
                                                }

                                                byte[] data = new byte[2];
                                                StringBuilder value = new StringBuilder();
                                                byte start_reg = Payload[0];
                                                byte current_reg = 0;

                                                for (int i = 0; i < SMBusRegisterDumpList.Count; i++)
                                                {
                                                    data[0] = (byte)(SMBusRegisterDumpList[i] >> 8 & 0xFF);
                                                    data[1] = (byte)(SMBusRegisterDumpList[i] & 0xFF);
                                                    current_reg = (byte)(i + start_reg);
                                                    value.Append("[" + Util.ByteToHexString(new byte[] { current_reg }, 0, 1) + "]: " + Util.ByteToHexString(data, 0, data.Length) + " // ");

                                                    switch (current_reg)
                                                    {
                                                        case 0x00:
                                                            value.Append("ManufacturerAccess: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        case 0x01:
                                                            if (DesignVoltage > 0) value.Append("RemainingCapacityAlarm: " + SMBusRegisterDumpList[i].ToString() + " mAh = " + Math.Round((DesignVoltage / 1000D) * SMBusRegisterDumpList[i]).ToString("0") + " mWh");
                                                            else value.Append("RemainingCapacityAlarm: " + SMBusRegisterDumpList[i].ToString() + " mAh");
                                                            break;
                                                        case 0x02:
                                                            value.Append("RemainingTimeAlarm: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x03:
                                                            value.Append("BatteryMode: " + Convert.ToString(SMBusRegisterDumpList[i], 2).PadLeft(16, '0'));
                                                            break;
                                                        case 0x04:
                                                            value.Append("AtRate: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x05:
                                                            value.Append("AtRateTimeToFull: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x06:
                                                            value.Append("AtRateTimeToEmpty: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x07:
                                                            string state;
                                                            if (SMBusRegisterDumpList[i] == 0) state = "false";
                                                            else state = "true";
                                                            value.Append("AtRateOK: " + state);
                                                            break;
                                                        case 0x08:
                                                            Double Temperature = Math.Round((SMBusRegisterDumpList[i] - 273.15) / 100, 2);
                                                            value.Append("Temperature: " + Temperature + "°C");
                                                            break;
                                                        case 0x09:
                                                            Double Voltage = SMBusRegisterDumpList[i] / 1000D;
                                                            value.Append("Voltage: " + Voltage + " V");
                                                            break;
                                                        case 0x0A:
                                                            Double Current = SMBusRegisterDumpList[i] / 1000D;
                                                            value.Append("Current: " + Current + " A");
                                                            break;
                                                        case 0x0B:
                                                            Double AverageCurrent = SMBusRegisterDumpList[i] / 1000D;
                                                            value.Append("AverageCurrent: " + AverageCurrent + " A");
                                                            break;
                                                        case 0x0C:
                                                            value.Append("MaxError: " + SMBusRegisterDumpList[i].ToString() + "%");
                                                            break;
                                                        case 0x0D:
                                                            value.Append("RelativeStateOfCharge: " + SMBusRegisterDumpList[i].ToString() + "%");
                                                            break;
                                                        case 0x0E:
                                                            value.Append("AbsoluteStateOfCharge: " + SMBusRegisterDumpList[i].ToString() + "%");
                                                            break;
                                                        case 0x0F:
                                                            value.Append("RemainingCapacity: " + SMBusRegisterDumpList[i].ToString() + " mAh");
                                                            break;
                                                        case 0x10:
                                                            value.Append("FullChargeCapacity: " + SMBusRegisterDumpList[i].ToString() + " mAh");
                                                            break;
                                                        case 0x11:
                                                            value.Append("RunTimeToEmpty: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x12:
                                                            value.Append("AverageTimeToEmpty: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x13:
                                                            value.Append("AverageTimeToFull: " + SMBusRegisterDumpList[i].ToString() + " minutes");
                                                            break;
                                                        case 0x14:
                                                            Double ChargingCurrent = SMBusRegisterDumpList[i] / 1000D;
                                                            value.Append("ChargingCurrent: " + ChargingCurrent + " A");
                                                            break;
                                                        case 0x15:
                                                            Double ChargingVoltage = SMBusRegisterDumpList[i] / 1000D;
                                                            value.Append("ChargingVoltage: " + ChargingVoltage + " V");
                                                            break;
                                                        case 0x16:
                                                            value.Append("BatteryStatus: " + Convert.ToString(SMBusRegisterDumpList[i], 2).PadLeft(16, '0'));
                                                            break;
                                                        case 0x17:
                                                            value.Append("CycleCount: " + SMBusRegisterDumpList[i].ToString());
                                                            break;
                                                        case 0x18:
                                                            value.Append("DesignCapacity: " + SMBusRegisterDumpList[i].ToString() + " mAh");
                                                            break;
                                                        case 0x19:
                                                            DesignVoltage = SMBusRegisterDumpList[i];
                                                            value.Append("DesignVoltage: " + (DesignVoltage / 1000D).ToString() + " V");
                                                            break;
                                                        case 0x1A:
                                                            value.Append("SpecificationInfo: " + Convert.ToString(SMBusRegisterDumpList[i], 2).PadLeft(16, '0'));
                                                            break;
                                                        case 0x1B:
                                                            int year = 1980 + ((SMBusRegisterDumpList[i] >> 9) & 0x7F);
                                                            int month = (SMBusRegisterDumpList[i] >> 5) & 0x0F;
                                                            int day = SMBusRegisterDumpList[i] & 0x1F;
                                                            DateTime Date = new DateTime(year, month, day);
                                                            value.Append("ManufactureDate: " + Date.ToString("yyyy.MM.dd"));
                                                            break;
                                                        case 0x1C:
                                                            value.Append("SerialNumber: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        case 0x20:
                                                            value.Append("ManufacturerName: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        case 0x21:
                                                            value.Append("DeviceName: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        case 0x22:
                                                            value.Append("DeviceChemistry: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        case 0x23:
                                                            value.Append("ManufacturerData: " + Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                        default:
                                                            value.Append(Util.ByteToHexString(data, 0, data.Length));
                                                            break;
                                                    }

                                                    if (i != (SMBusRegisterDumpList.Count - 1)) value.Append(Environment.NewLine);
                                                }

                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] SMBus register dump details (" + Util.ByteToHexString(Payload, 0, 1) + "-" + Util.ByteToHexString(Payload, 1, 2) + "):" + Environment.NewLine + value.ToString(), null);
                                            }
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                            break;
                                    }
                                    break;
                                case 0x03: // settings
                                    switch (SubDataCode)
                                    {
                                        case 0x01: // current settings
                                        case 0x03:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Device settings", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                WordByteOrderComboBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    WordByteOrderComboBox.SelectedIndex = Payload[0];
                                                });

                                                string reverse = string.Empty;
                                                if ((Payload[0] & 0x03) == 0) reverse = "no reverse";
                                                else if ((Payload[0] & 0x03) == 1) reverse = "reverse read";
                                                else if ((Payload[0] & 0x03) == 2) reverse = "reverse write";
                                                else if ((Payload[0] & 0x03) == 3) reverse = "reverse read/write";
                                                else reverse = "unknown";
                                                DesignVoltage = (ushort)((Payload[1] << 8) + Payload[2]);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Word byte-order: " + reverse, null);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Design voltage: " + (DesignVoltage / 1000D).ToString("0.0") + " V", null);
                                            }
                                            break;
                                        case 0x02: // select smbus address
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] SMBus settings", Packet);
                                            Util.UpdateTextBox(CommunicationTextBox, "[INFO] Current SMBus device address: " + Util.ByteToHexString(Payload, 0, 1), null);
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                            break;
                                    }
                                    break;
                                case 0x04: // read data
                                    switch (SubDataCode)
                                    {
                                        case 0x01: // read byte data
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Byte data received", Packet);
                                            if (Payload.Length > 1)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Util.ByteToHexString(Payload, 1, 2);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data, null);

                                                ReadDataTextBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    ReadDataTextBox.Text = data;
                                                });
                                            }
                                            break;
                                        case 0x02: // read word data
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Word data received", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Util.ByteToHexString(Payload, 1, 3);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data, null);

                                                ReadDataTextBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    ReadDataTextBox.Text = data;
                                                });
                                            }
                                            break;
                                        case 0x03: // read block data
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Block data received", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Encoding.ASCII.GetString(Payload, 2, Payload.Length - 2);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data, null);

                                                ReadDataTextBox.BeginInvoke((MethodInvoker)delegate
                                                {
                                                    ReadDataTextBox.Text = data;
                                                });
                                            }
                                            break;
                                        case 0x04: // read rom byte
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] ROM byte data received", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string address = Util.ByteToHexString(Payload, 0, 2);
                                                string data = Util.ByteToHexString(Payload, 2, Payload.Length);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] ROM address: " + address + "; Data:" + Environment.NewLine + data, null);

                                                // Save data to a binary file
                                                using (BinaryWriter writer = new BinaryWriter(File.Open(ROMBinaryFilename, FileMode.Append)))
                                                {
                                                    writer.Write(Payload, 2, Payload.Length - 2);
                                                    writer.Close();
                                                }
                                            }
                                            break;
                                        case 0x05: // read rom block
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] ROM block data received", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string address = Util.ByteToHexString(Payload, 0, 2);
                                                string data = Util.ByteToHexString(Payload, 2, Payload.Length);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] ROM address: " + address + "; Data:" + Environment.NewLine + data, null);

                                                // Save data to a binary file
                                                using (BinaryWriter writer = new BinaryWriter(File.Open(ROMBinaryFilename, FileMode.Append)))
                                                {
                                                    writer.Write(Payload, 2, Payload.Length - 2);
                                                    writer.Close();
                                                }
                                            }
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                            break;
                                    }
                                    break;
                                case 0x05: // write data
                                    switch (SubDataCode)
                                    {
                                        case 0x01: // write data byte
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Byte data write response", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Util.ByteToHexString(Payload, 1, 2);
                                                string success = Util.ByteToHexString(Payload, 2, 3);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data + Environment.NewLine +
                                                                                            "       # of bytes written: " + success, null);
                                            }
                                            break;
                                        case 0x02: // write data word
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Word data write response", Packet);
                                            if (Payload.Length > 3)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Util.ByteToHexString(Payload, 1, 3);
                                                string success = Util.ByteToHexString(Payload, 3, 4);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data + Environment.NewLine +
                                                                                            "       # of bytes written: " + success, null);
                                            }
                                            break;
                                        case 0x03: // write data block
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Block data write response", Packet);
                                            if (Payload.Length > 2)
                                            {
                                                string register = Util.ByteToHexString(Payload, 0, 1);
                                                string data = Util.ByteToHexString(Payload, 1, Payload.Length - 1);
                                                string success = Util.ByteToHexString(Payload, Payload.Length - 1, Payload.Length);
                                                Util.UpdateTextBox(CommunicationTextBox, "[INFO] Reg.: " + register + Environment.NewLine +
                                                                                            "       Data: " + data + Environment.NewLine +
                                                                                            "       # of bytes written: " + success, null);
                                            }
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                            break;
                                    }
                                    break;
                                case 0x0F: // OK/Error
                                    switch (SubDataCode)
                                    {
                                        case 0x00:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] OK", Packet);
                                            break;
                                        case 0x01:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: invalid length", Packet);
                                            break;
                                        case 0x02:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: invalid command", Packet);
                                            break;
                                        case 0x03:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: invalid sub-data code", Packet);
                                            break;
                                        case 0x04:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: invalid payload value(s)", Packet);
                                            break;
                                        case 0x05:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: invalid checksum", Packet);
                                            break;
                                        case 0x06:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: packet timeout occured", Packet);
                                            break;
                                        case 0xFD:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: not enough MCU RAM", Packet);
                                            break;
                                        case 0xFE:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: internal error", Packet);
                                            break;
                                        case 0xFF:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Error: fatal error", Packet);
                                            break;
                                        default:
                                            Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                            break;
                                    }
                                    break;
                                default:
                                    Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received", Packet);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        Util.UpdateTextBox(CommunicationTextBox, "[RX->] Data received with checksum error", Packet);
                    }

                    bufferlist.RemoveRange(0, Packet.Length);
                }
                else
                {
                    bufferlist.RemoveAt(0); // remove this byte and see what's next
                }
                break;
            }
        }

19 Source : SCIPCMDiagnosticsTable.cs
with GNU General Public License v3.0
from laszlodaniel

public void AddRow(ushort modifiedID, string row)
        {
            int location = 0;

            if (!IDByteList.Contains(modifiedID))
            {
                byte uniqueID = (byte)((modifiedID >> 8) & 0xFF);
                if (!UniqueIDByteList.Contains(uniqueID)) UniqueIDByteList.Add(uniqueID);

                IDByteList.Add(modifiedID);
                IDByteList.Sort();
                location = IDByteList.FindIndex(x => x == modifiedID);

                if (IDByteList.Count == 1)
                {
                    Table.RemoveAt(listStart);
                    Table.Insert(listStart, row);
                }
                else
                {
                    Table.Insert(listStart + location, row);
                }

                lastUpdatedLine = listStart + location;
            }
            else
            {
                location = IDByteList.FindIndex(x => x == modifiedID);
                Table.RemoveAt(listStart + location);
                Table.Insert(listStart + location, row);
                lastUpdatedLine = listStart + location;
            }
        }

19 Source : QMonoBehaviour.cs
with MIT License
from liangxiegame

protected void RegisterEvent<T>(T eventId) where T : IConvertible
		{
			mCachedEventIds.Add(eventId.ToUInt16(null));
			Manager.RegisterEvent(eventId, Process);
		}

19 Source : SaveFileProfileData.cs
with Apache License 2.0
from LIPtoH

public void Prepare(string[] _FileLines)
        {
            string[] chunkOfline;
            char[] CharsToTrim = new char[] { '"' };

            for (int line = 0; line < _FileLines.Length; line++)
            {
                if (_FileLines[line].StartsWith("user_profile :"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    UserProfileNameless = chunkOfline[2];
                    continue;
                }

                if (_FileLines[line].StartsWith(" face:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    Face = ushort.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" brand:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    Brand = chunkOfline[2];
                    continue;
                }

                if (_FileLines[line].StartsWith(" map_path:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    MapPath = chunkOfline[2];
                    continue;
                }

                if (_FileLines[line].StartsWith(" logo:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    Logo = chunkOfline[2];
                    continue;
                }

                if (_FileLines[line].StartsWith(" company_name:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' }, 3);
                    string result = "";

                    if (chunkOfline[2].StartsWith("\"") && chunkOfline[2].EndsWith("\""))
                    {
                        string compNameH = chunkOfline[2].Remove(chunkOfline[2].Length - 1, 1).Remove(0, 1);

                        result = Utilities.TextUtilities.FromUtfHexToString(compNameH);
                    }

                    CompanyName = (result == "") ? chunkOfline[2] : result;

                    continue;
                }

                if (_FileLines[line].StartsWith(" male:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    GenederMale = bool.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" cached_experience:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CachedExperiencePoints = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" cached_distance:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CachedDistance = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[0]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SomeTimeUD0 = (chunkOfline[2] != "\"\"") ? uint.Parse(chunkOfline[2].Trim(CharsToTrim)) : (uint?)null;
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[1]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    LicensePlateUD1 = (chunkOfline[2] != "\"\"") ? chunkOfline[2].Trim(CharsToTrim) : null;
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[2]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SomeCheckSumUD2 = (chunkOfline[2] != "\"\"") ? chunkOfline[2].Trim(CharsToTrim) : null;
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[3]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    WoTConnectedUD3 = (chunkOfline[2] != "\"\"") ? byte.Parse(chunkOfline[2].Trim(CharsToTrim)) : (byte?)null;
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[4]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    RoadsExploredUD4 = decimal.Parse(chunkOfline[2].Trim(CharsToTrim), System.Globalization.CultureInfo.InvariantCulture);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[5]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    DeliveriesFinishedUD5 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[6]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OwnedTrucksUD6 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[7]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OwnedGaradesSmallUD7 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[8]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OwnedGaradesLargeUD8 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[9]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    GameTimeSpentUD9 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[10]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    RealTimeSpentUD10 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[11]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CurrentTruckUD11 = chunkOfline[2].Trim(CharsToTrim);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[12]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OwnedTruckListUD12 = chunkOfline[2].Trim(CharsToTrim).Split(new char[] { ',' }).ToList();
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[13]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SomeUserDataUD13 = chunkOfline[2].Trim(CharsToTrim);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[14]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SomeUserDataUD14 = (chunkOfline[2] != "\"\"") ? uint.Parse(chunkOfline[2].Trim(CharsToTrim)) : (uint?)null;
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[15]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SomeUserDataUD15 = chunkOfline[2].Trim(CharsToTrim);
                    continue;
                }

                if (_FileLines[line].StartsWith(" user_data[16]:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OwnedTrailersUD16 = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" active_mods:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    ActiveMods = new List<string>(int.Parse(chunkOfline[2]));

                    for (int x = 0; x < ActiveMods.Capacity; x++)
                    {
                        line++;
                        chunkOfline = _FileLines[line].Split(new char[] { ' ' }, 3);
                        ActiveMods.Add(chunkOfline[2]);
                    }
                    continue;
                }

                if (_FileLines[line].StartsWith(" customization:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    Customization = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" cached_stats:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CachedStats = new List<ushort>(int.Parse(chunkOfline[2]));

                    for (int x = 0; x < CachedStats.Capacity; x++)
                    {
                        line++;
                        chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                        CachedStats.Add(ushort.Parse(chunkOfline[2]));
                    }
                    continue;
                }

                if (_FileLines[line].StartsWith(" cached_discovery:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CachedDiscovery = new List<ushort>(int.Parse(chunkOfline[2]));

                    for (int x = 0; x < CachedDiscovery.Capacity; x++)
                    {
                        line++;
                        chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                        CachedDiscovery.Add(ushort.Parse(chunkOfline[2]));
                    }
                    continue;
                }

                if (_FileLines[line].StartsWith(" version:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    Version = byte.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" online_user_name:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OnlineUserName = chunkOfline[2].Trim(CharsToTrim);
                    continue;
                }

                if (_FileLines[line].StartsWith(" online_preplacedword:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    OnlinePreplacedword = chunkOfline[2].Trim(CharsToTrim);
                    continue;
                }

                if (_FileLines[line].StartsWith(" profile_name:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' }, 3);

                    string result = null;

                    if (chunkOfline[2].StartsWith("\"") && chunkOfline[2].EndsWith("\""))
                    {
                        string compNameH = chunkOfline[2].Substring(1, chunkOfline[2].Length - 2);

                        if (compNameH.Contains("\\x"))                        
                            result = Utilities.TextUtilities.FromHexToString(string.Join("", compNameH.Split(new string[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries)));
                        
                        if (result == null)
                            result = System.Text.RegularExpressions.Regex.Unescape(compNameH);
                    }

                    ProfileName = (result == null) ? chunkOfline[2] : result;

                    continue;
                }

                if (_FileLines[line].StartsWith(" creation_time:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    CreationTime = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith(" save_time:"))
                {
                    chunkOfline = _FileLines[line].Split(new char[] { ' ' });
                    SaveTime = uint.Parse(chunkOfline[2]);
                    continue;
                }

                if (_FileLines[line].StartsWith("}"))
                {
                    break;
                }
            }
        }

19 Source : MapGeometryOBJExtensions.cs
with GNU General Public License v3.0
from LoL-Fantome

public static (List<ushort>, List<MapGeometryVertex>) GetMGEOData(this OBJFile obj)
        {
            List<ushort> indices = new List<ushort>();
            List<MapGeometryVertex> vertices = new List<MapGeometryVertex>();

            foreach (Vector3 vertex in obj.Vertices)
            {
                vertices.Add(new MapGeometryVertex() { Position = vertex });
            }

            foreach (OBJFace face in obj.Faces)
            {
                for (int i = 0; i < 3; i++)
                {
                    indices.Add((ushort)face.VertexIndices[i]);
                }

                if (face.NormalIndices != null)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        vertices[(int)face.VertexIndices[i]].Normal = obj.Normals[(int)face.NormalIndices[i]];
                    }
                }

                if (face.UVIndices!= null)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        vertices[(int)face.VertexIndices[i]].DiffuseUV = obj.UVs[(int)face.UVIndices[i]];
                    }
                }
            }

            return (indices, vertices);
        }

19 Source : PdfDomFont.cs
with MIT License
from Macad3D

public override bool Write(PdfWriter writer)
        {
            if (!_Completed)
            {
                Attributes["Subtype"] = "/TrueType";
                Attributes["Encoding"] = "/WinAnsiEncoding";
                Attributes["Name"] = $"/{_Name}";
                string finalFontName = $"{_Style.Family.Replace(" ", "")}";
                
                var typeface = new Typeface(new FontFamily(_Style.Family), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
                if (typeface.TryGetGlyphTypeface(out var glyphTypeface))
                {
                    var ciEnUs = CultureInfo.GetCultureInfo("en-us");
                    finalFontName = (glyphTypeface.FamilyNames[ciEnUs] + glyphTypeface.FaceNames[ciEnUs]).Replace(" ", "");
                    Attributes["FirstChar"] = _FirstChar;
                    Attributes["LastChar"] = _LastChar;
                    Attributes["FontDescriptor"] = _Descriptor;

                    // Create list of glyphs and widths
                    int[] widths = new int[_LastChar - _FirstChar + 1];
                    List<ushort> glyphs = new();
                    for (int i = _FirstChar; i <= _LastChar; i++)
                    {
                        if (!_Characters.Contains(i) || !glyphTypeface.CharacterToGlyphMap.ContainsKey(i))
                            continue;

                        ushort glyph = glyphTypeface.CharacterToGlyphMap[i];
                        widths[i - _FirstChar] = (glyphTypeface.AdvanceWidths[glyph] * 1000.0).ToRoundedInt();
                        glyphs.Add(glyph);
                    }
                    Attributes["Widths"] = widths;

                    _Descriptor.Update(glyphTypeface, glyphs, ref finalFontName);
                }

                Attributes["BaseFont"] = $"/{finalFontName}";

                _Completed = true;
            }

            return _Descriptor.Write(writer) && base.Write(writer);
        }

19 Source : 4DSLoader.cs
with Apache License 2.0
from MafiaHub

Target readTarget(BinaryReader reader)
        {
            Target newTarget = new Target();
            newTarget.unk0 = reader.ReadUInt16();
            var targetCount = reader.ReadByte();

            newTarget.targets = new List<ushort>();

            for (var i = 0; i < targetCount; i++)
                newTarget.targets.Add(reader.ReadUInt16());


            return newTarget;
        }

19 Source : 4DSLoader.cs
with Apache License 2.0
from MafiaHub

Morph readMorph(BinaryReader reader, bool ignoreStandard)
        {
            Morph newMorph = new Morph();

            // NOTE(zaklaus): Single Morph contains Standard Mesh in Single Mesh already.
            if (!ignoreStandard)
            {
                newMorph.standard = readStandard(reader);
            }
            // NOTE(zaklaus): ELSE ignore Standard Mesh, since Single Mesh has it.
            newMorph.frameCount = reader.ReadByte();
            if (newMorph.frameCount > 0)
            {
                var LODLevel = reader.ReadByte();
                newMorph.unk0 = reader.ReadByte();

                newMorph.LODs = new List<MorphLOD>();

                for (var i = 0; i < LODLevel; i++)
                {
                    MorphLOD newMorphLOD = new MorphLOD();
                    var vertexCount = reader.ReadUInt16();

                    newMorphLOD.vertices = new List<MorphLODVertex>();

                    for (var j = 0; j < newMorph.frameCount * vertexCount; j++)
                    {
                        MorphLODVertex newVertex = new MorphLODVertex();
                        newVertex.normals = ReadVector3(reader);
                        newVertex.position = ReadVector3(reader);

                        newMorphLOD.vertices.Add(newVertex);
                    }

                    if (newMorph.frameCount * vertexCount > 0)
                        newMorphLOD.unk0 = reader.ReadByte();

                    newMorphLOD.vertexLinks = new List<ushort>();

                    for (var j = 0; j < vertexCount; j++)
                        newMorphLOD.vertexLinks.Add(reader.ReadUInt16());

                    newMorph.LODs.Add(newMorphLOD);
                }

                newMorph.minBox = ReadVector3(reader);
                newMorph.maxBox = ReadVector3(reader);

                newMorph.unk1 = new float[4];
                for (var i = 0; i < 4; i++)
                    newMorph.unk1[i] = reader.ReadSingle();
            }

            return newMorph;
        }

19 Source : SellAgent.cs
with GNU General Public License v3.0
from markdwags

public override void Load(XmlElement node)
        {
            try
            {
                m_Enabled = bool.Parse(node.GetAttribute("enabled"));
            }
            catch
            {
                m_Enabled = false;
            }

            try
            {
                m_HotBag = node["hotbag"] != null ? Serial.Parse(node["hotbag"].InnerText) : Serial.Zero;
            }
            catch
            {
                m_HotBag = Serial.Zero;
            }

            foreach (XmlElement el in node.GetElementsByTagName("item"))
            {
                try
                {
                    string str = el.GetAttribute("id");
                    m_Items.Add(Convert.ToUInt16(str));
                }
                catch
                {
                    // ignored
                }
            }
        }

19 Source : EncodedSpeech.cs
with GNU General Public License v3.0
from markdwags

internal static List<ushort> GetKeywords(string text)
        {
            List<ushort> keynumber = new List<ushort>();

            if (m_Speech == null)
            {
                LoadSpeechTable();
            }

            text = text.ToLower();

            List<SpeechEntry> keywords = new List<SpeechEntry>();
            List<SpeechEntry> speech = m_Speech.ToList();
            foreach (SpeechEntry entry in speech)
            {
                if (IsMatch(text, entry.m_Keywords))
                {
                    keywords.Add(entry);
                }
            }

            keywords.Sort();

            bool flag = false;

            int numk = keywords.Count & 15;
            int index = 0;
            while (index < keywords.Count)
            {
                SpeechEntry entry = keywords[index];
                int keywordID = entry.m_KeywordID;

                if (flag)
                {
                    keynumber.Add((byte) (keywordID >> 4));
                    numk = keywordID & 15;
                }
                else
                {
                    keynumber.Add((byte) ((numk << 4) | ((keywordID >> 8) & 15)));
                    keynumber.Add((byte) keywordID);
                }

                index++;
                flag = !flag;
            }

            if (!flag)
            {
                keynumber.Add((byte) (numk << 4));
            }

            return keynumber;
        }

19 Source : SellAgent.cs
with GNU General Public License v3.0
from markdwags

public void Add(ItemID itemId)
        {
            m_Items?.Add(itemId);
            m_SubList?.Items.Add((ItemID)itemId);

            World.Player?.SendMessage(MsgLevel.Force, LocString.ItemAdded);
        }

19 Source : Structs.cs
with GNU General Public License v3.0
from mazmazz

public List<ushort> GetGroupIDs(Stream stream)
        {
            List<ushort> groupIconIDs = new List<ushort>();
            for(int i=0; i<rscTypes.Length; i++)
            {
                if (rscTypes[i].ResourceType != ResourceType.RT_GROUP_ICON)
                    continue;

                for(int j=0; j<rscTypes[i].rtNameInfo.Length; j++)
                    groupIconIDs.Add(rscTypes[i].rtNameInfo[j].ID);
                break;
            }
            return groupIconIDs;
        }

19 Source : FileTestBase.cs
with MIT License
from mbbsemu

protected ushort f_printf(FarPtr filep, string formatString, params object[] values)
        {
            var fprintfParameters = new List<ushort> {filep.Offset, filep.Segment};

            //Add Formatted String
            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(formatString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(formatString));
            fprintfParameters.Add(inputStingParameterPointer.Offset);
            fprintfParameters.Add(inputStingParameterPointer.Segment);

            //Add Parameters
            var parameterList = GenerateParameters(values);
            fprintfParameters.AddRange(parameterList);

            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, FPRINTF_ORDINAL, fprintfParameters);

            return mbbsEmuCpuRegisters.AX;
        }

19 Source : spr_Tests.cs
with MIT License
from mbbsemu

[Theory]
        [InlineData("%d", "1", (ushort)1)]
        [InlineData("%s", "Test", "Test")]
        public void spr_Test(string inputString, string expectedString, params object[] values)
        {
            Reset();

            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(inputString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(inputString));
            _parameters.Add(inputStingParameterPointer.Offset);
            _parameters.Add(inputStingParameterPointer.Segment);

            foreach (var v in values)
            {
                switch (v)
                {
                    case string @parameterString:
                        {
                            var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
                            mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
                            _parameters.Add(stringParameterPointer.Offset);
                            _parameters.Add(stringParameterPointer.Segment);
                            break;
                        }
                    case uint @parameterULong:
                        {
                            var longBytes = BitConverter.GetBytes(@parameterULong);
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                            break;
                        }
                    case int @parameterLong:
                        {
                            var longBytes = BitConverter.GetBytes(@parameterLong);
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                            break;
                        }
                    case ushort @parameterInt:
                        _parameters.Add(@parameterInt);
                        break;
                }
            }

            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);

            replacedert.Equal(expectedString, Encoding.ASCII.GetString(mbbsEmuMemoryCore.GetString(mbbsEmuCpuRegisters.GetPointer(), true)));
        }

19 Source : spr_Tests.cs
with MIT License
from mbbsemu

[Theory]
        [InlineData("%d", "1", (ushort)1)]
        [InlineData("%s", "Test", "Test")]
        public void spr_Test(string inputString, string expectedString, params object[] values)
        {
            Reset();

            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(inputString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(inputString));
            _parameters.Add(inputStingParameterPointer.Offset);
            _parameters.Add(inputStingParameterPointer.Segment);

            foreach (var v in values)
            {
                switch (v)
                {
                    case string @parameterString:
                        {
                            var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
                            mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
                            _parameters.Add(stringParameterPointer.Offset);
                            _parameters.Add(stringParameterPointer.Segment);
                            break;
                        }
                    case uint @parameterULong:
                        {
                            var longBytes = BitConverter.GetBytes(@parameterULong);
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                            break;
                        }
                    case int @parameterLong:
                        {
                            var longBytes = BitConverter.GetBytes(@parameterLong);
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                            _parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                            break;
                        }
                    case ushort @parameterInt:
                        _parameters.Add(@parameterInt);
                        break;
                }
            }

            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);

            replacedert.Equal(expectedString, Encoding.ASCII.GetString(mbbsEmuMemoryCore.GetString(mbbsEmuCpuRegisters.GetPointer(), true)));
        }

19 Source : spr_Tests.cs
with MIT License
from mbbsemu

[Fact]
        public void spr_Limit_Test()
        {
            Reset();

            var inputString = "%s";
            var parameterString = new string('X', 2000);

            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(inputString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(inputString));
            _parameters.Add(inputStingParameterPointer.Offset);
            _parameters.Add(inputStingParameterPointer.Segment);

            var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
            mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
            _parameters.Add(stringParameterPointer.Offset);
            _parameters.Add(stringParameterPointer.Segment);


            replacedert.Throws<OutOfMemoryException>(() => ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters));
        }

19 Source : ExportedModuleTestBase.cs
with MIT License
from mbbsemu

protected void ExecuteApiTest(ushort exportedModuleSegment, ushort apiOrdinal, IEnumerable<FarPtr> apiArguments)
        {
            var argumentsList = new List<ushort>(apiArguments.Count() * 2);

            foreach (var a in apiArguments)
            {
                argumentsList.Add(a.Offset);
                argumentsList.Add(a.Segment);
            }

            ExecuteApiTest(exportedModuleSegment, apiOrdinal, argumentsList);
        }

19 Source : ExportedModuleTestBase.cs
with MIT License
from mbbsemu

protected List<ushort> GenerateParameters(object[] values)
        {
            var parameters = new List<ushort>();
            foreach (var v in values)
            {
                switch (v)
                {
                    case string @parameterString:
                    {
                        var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
                        mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
                        parameters.Add(stringParameterPointer.Offset);
                        parameters.Add(stringParameterPointer.Segment);
                        break;
                    }
                    case uint @parameterULong:
                    {
                        var longBytes = BitConverter.GetBytes(@parameterULong);
                        parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                        parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                        break;
                    }
                    case int @parameterLong:
                    {
                        var longBytes = BitConverter.GetBytes(@parameterLong);
                        parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                        parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                        break;
                    }
                    case ushort @parameterUInt:
                        parameters.Add(@parameterUInt);
                        break;

                    case short @parameterInt:
                        parameters.Add((ushort)@parameterInt);
                        break;
                }
            }

            return parameters;
        }

19 Source : spr_Tests.cs
with MIT License
from mbbsemu

[Fact]
        public void spr_Increment_Test()
        {
            Reset();

            var inputString = "%s";
            var parameterString = new string('X', 100);

            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(inputString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(inputString));
            _parameters.Add(inputStingParameterPointer.Offset);
            _parameters.Add(inputStingParameterPointer.Segment);

            var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
            mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
            _parameters.Add(stringParameterPointer.Offset);
            _parameters.Add(stringParameterPointer.Segment);

            var pointers = new List<FarPtr>();
            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);
            pointers.Add(mbbsEmuCpuRegisters.GetPointer());
            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);
            pointers.Add(mbbsEmuCpuRegisters.GetPointer());
            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);
            pointers.Add(mbbsEmuCpuRegisters.GetPointer());
            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);
            pointers.Add(mbbsEmuCpuRegisters.GetPointer());
            replacedert.Equal(pointers.Count, pointers.GroupBy(x=> x).Count());

            //Test the variable pointer rolls over to the first
            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, SPR_ORDINAL, _parameters);
            pointers.Add(mbbsEmuCpuRegisters.GetPointer());
            replacedert.NotEqual(pointers.Count, pointers.GroupBy(x => x).Count()); //count should be higher than the aggregate
        }

19 Source : prf_Tests.cs
with MIT License
from mbbsemu

[Theory]
        [InlineData("%d", "1", (ushort)1)]
        [InlineData("%d", "0", (ushort)0)]
        [InlineData("%d", "-1", (ushort)0xFFFF)]
        [InlineData("%u", "1", (ushort)1)]
        [InlineData("%u", "0", (ushort)0)]
        [InlineData("%u", "65535", (ushort)0xFFFF)]
        [InlineData("ITEM%3.3d", "ITEM010", (ushort)10)]
        [InlineData("ITEM%3d", "ITEM 10", (ushort)10)]
        [InlineData("ITEM%3.3d", "ITEM100", (ushort)100)]
        [InlineData("ITEM%3d", "ITEM100", (ushort)100)]
        [InlineData("Level: %5d", "Level:     3", (ushort)3)]
        [InlineData("Level: %-5d", "Level: 3    ", (ushort)3)]
        [InlineData("Level: %5.5d", "Level: 00003", (ushort)3)]
        [InlineData("Level: %-5.5d", "Level: 00003", (ushort)3)]
        [InlineData("%s-%d", "TEST-1", "TEST", (ushort)1)]
        [InlineData("%s-%ld", "TEST-2147483647", "TEST", 2147483647)]
        [InlineData("%s-%ld-%d-%s", "TEST-2147483647-1-FOO", "TEST", 2147483647, (ushort)1, "FOO")]
        [InlineData("%s-%ld-%d-%s", "TEST--1-1-FOO", "TEST", (uint)0xFFFFFFFF, (ushort)1, "FOO")]
        [InlineData("%s-%lu-%d-%s", "TEST-2147483647-1-FOO", "TEST", 2147483647u, (ushort)1, "FOO")]
        [InlineData("%s-%lu-%d-%s", "TEST-3147483647-1-FOO", "TEST", 3147483647u, (ushort)1, "FOO")]
        [InlineData("99% of the time, this will print %s", "99% of the time, this will print TEST", "TEST")] //Unescaped %
        [InlineData("Mid 50% Test", "Mid 50% Test", null)] //Unescaped %
        [InlineData("End 50% ", "End 50% ", null)] //Unescaped %
        [InlineData("End 50%", "End 50%", null)] //Unescaped %
        [InlineData("This is 100%% accurate", "This is 100% accurate", null)] //Escaped %
        [InlineData("%%%%", "%%", null)] //Escaped %
        [InlineData("%%%%%", "%%%", null)] //Escaped & Unescaped %
        [InlineData("%%%%% ", "%%% ", null)] //Escaped & Unescaped %
        public void prf_Test(string inputString, string expectedString, params object[] values)
        {
            Reset();

            var inputStingParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(inputString.Length + 1));
            mbbsEmuMemoryCore.SetArray(inputStingParameterPointer, Encoding.ASCII.GetBytes(inputString));
            parameters.Add(inputStingParameterPointer.Offset);
            parameters.Add(inputStingParameterPointer.Segment);

            if (values != null)
            {
                var parameterList = GenerateParameters(values);
                foreach (var p in parameterList)
                    parameters.Add(p);
            }

            ExecuteApiTest(HostProcess.ExportedModules.Majorbbs.Segment, PRF_ORDINAL, parameters);

            replacedert.Equal(expectedString, Encoding.ASCII.GetString(mbbsEmuMemoryCore.GetString("PRFBUF", true)));
        }

19 Source : ExportedModuleTestBase.cs
with MIT License
from mbbsemu

protected List<ushort> GenerateParameters(object[] values)
        {
            var parameters = new List<ushort>();
            foreach (var v in values)
            {
                switch (v)
                {
                    case string @parameterString:
                    {
                        var stringParameterPointer = mbbsEmuMemoryCore.AllocateVariable(Guid.NewGuid().ToString(), (ushort)(@parameterString.Length + 1));
                        mbbsEmuMemoryCore.SetArray(stringParameterPointer, Encoding.ASCII.GetBytes(@parameterString));
                        parameters.Add(stringParameterPointer.Offset);
                        parameters.Add(stringParameterPointer.Segment);
                        break;
                    }
                    case uint @parameterULong:
                    {
                        var longBytes = BitConverter.GetBytes(@parameterULong);
                        parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                        parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                        break;
                    }
                    case int @parameterLong:
                    {
                        var longBytes = BitConverter.GetBytes(@parameterLong);
                        parameters.Add(BitConverter.ToUInt16(longBytes, 0));
                        parameters.Add(BitConverter.ToUInt16(longBytes, 2));
                        break;
                    }
                    case ushort @parameterUInt:
                        parameters.Add(@parameterUInt);
                        break;

                    case short @parameterInt:
                        parameters.Add((ushort)@parameterInt);
                        break;
                }
            }

            return parameters;
        }

19 Source : ModelLoader.cs
with Mozilla Public License 2.0
from mcneel

public static dynamic AccessBuffer(Accessor.TypeEnum accessorType, int count, Accessor.ComponentTypeEnum componentType, int stride, byte[] arr)
        {
            dynamic result = null;

            var elementCount = count;                                   //how many times do we need to do this?
            var componentCount = GetTypeMultiplier(accessorType); ;     //each time we do this, how many times do I need to read the buffer?
            var byteCount = GetComponentTypeMultiplier(componentType);  //how many bytes is each component from ComponentTypeEnum
            var elementBytes = componentCount * byteCount;

            var strideDiff = stride > 0 ? stride - elementBytes : 0;

            using (var memoryStream = new MemoryStream(arr))
            using (var reader = new BinaryReader(memoryStream))
            {
                // TODO: clean this up
                switch (componentType)
                {
                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.BYTE:

                        var listSByte = new List<sbyte>();

                        //loop through element count

                        //loop through component count
                        //if stride, position the reader appropriately
                        // element bytes should be byteCount * componentCount
                        // stride diff should be stride - elementbytes

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listSByte.Add(reader.ReadSByte());
                            }
                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listSByte;

                        break;
                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.FLOAT:

                        var listSingle = new List<Single>();

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listSingle.Add(reader.ReadSingle());
                            }
                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listSingle;

                        break;

                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.SHORT:

                        var listShort = new List<Int16>();

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listShort.Add(reader.ReadInt16());
                            }
                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listShort;

                        break;

                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.UNSIGNED_BYTE:

                        var listByte = new List<byte>();

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listByte.Add(reader.ReadByte());
                            }
                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listByte;

                        break;
                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.UNSIGNED_INT:

                        var listUInt = new List<uint>();

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listUInt.Add(reader.ReadUInt32());
                            }
                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listUInt;

                        break;
                    case glTFLoader.Schema.Accessor.ComponentTypeEnum.UNSIGNED_SHORT:

                        var listUInt16 = new List<UInt16>();

                        for (int i = 0; i < elementCount; i++)
                        {
                            for (int j = 0; j < componentCount; j++)
                            {
                                listUInt16.Add(reader.ReadUInt16());
                            }

                            reader.BaseStream.Position += strideDiff;
                        }

                        result = listUInt16;

                        break;
                }

            }

            return result;
        }

19 Source : WindowsStoreAppHelper.cs
with MIT License
from microsoftarchive

static private ushort[] StringArrayToPzz(string[] strs)
        {
            List<ushort> pzz = new List<ushort>();
            for (int i = 0; i < strs.Length; i++)
            {
                for (int j = 0; j < strs[i].Length; j++)
                {
                    pzz.Add((ushort)strs[i][j]);
                }
                // Null-terminate each contained string
                pzz.Add(0);
            }
            // Extra-null-terminate the entire pzz
            pzz.Add(0);

            return pzz.ToArray();
        }

19 Source : GeometricPrimitive.cs
with Microsoft Public License
from microsoftarchive

protected void AddIndex(int index)
        {
            if (index > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("index");

            indices.Add((ushort)index);
        }

19 Source : AckSystem.cs
with MIT License
from MirageNet

public void OnSend(ushort sequence)
            {
                sequences.Add(sequence);
                lastSequence = sequence;
            }

19 Source : GetGroupMembershipCommand.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            // Create lists
            GroupList = new List<ushort>();

            byte? groupCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (groupCount != null)
            {
                for (int cnt = 0; cnt < groupCount; cnt++)
                {
                    GroupList.Add((ushort) deserializer.Deserialize(DataType.UNSIGNED_16_BIT_INTEGER));
                }
            }
        }

19 Source : GetGroupMembershipResponse.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            // Create lists
            GroupList = new List<ushort>();

            Capacity = deserializer.Deserialize<byte>(DataType.UNSIGNED_8_BIT_INTEGER);
            byte? groupCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (groupCount != null)
            {
                for (int cnt = 0; cnt < groupCount; cnt++)
                {
                    GroupList.Add((ushort) deserializer.Deserialize(DataType.UNSIGNED_16_BIT_INTEGER));
                }
            }
        }

19 Source : DefaultDeserializer.cs
with Eclipse Public License 1.0
from Mr-Markus

public T ReadZigBeeType<T>(DataType type)
        {
            if (index == payload.Length)
            {
                return default(T);
            }

            object[] value = new object[1];
            switch (type)
            {
                case DataType.BOOLEAN:
                    value[0] = payload[index++] == 0 ? false : true;
                    break;
                case DataType.RAW_OCTET:
                    int rawSize = payload.Length - index;
                    value[0] = new ByteArray(payload, index, index + rawSize);
                    index += rawSize;
                    break;
                case DataType.OCTET_STRING:
                    int octetSize = payload[index++];
                    value[0] = new ByteArray(payload, index, index + octetSize);
                    index += octetSize;
                    break;
                case DataType.CHARACTER_STRING:
                    int stringSize = payload[index++];
                    if (stringSize == 255)
                    {
                        value[0] = null;
                        break;
                    }
                    byte[] bytes = new byte[stringSize];
                    int length = stringSize;
                    for (int cnt = 0; cnt < stringSize; cnt++)
                    {
                        bytes[cnt] = (byte)payload[index + cnt];
                        if (payload[index + cnt] == 0)
                        {
                            length = cnt;
                            break;
                        }
                    }
                    try
                    {
                        int len = length - 0;
                        byte[] dest = new byte[len];
                        // note i is always from 0
                        for (int i = 0; i < len; i++)
                        {
                            dest[i] = bytes[0 + i]; // so 0..n = 0+x..n+x
                        }

                        value[0] = Encoding.Default.GetString(dest);
                    }
                    catch (Exception)
                    {
                        value[0] = null;
                        break;
                    }
                    index += stringSize;
                    break;
                case DataType.LONG_OCTET_STRING:
                    int longOctetSize = (short)(payload[index++] + (payload[index++] << 8));
                    value[0] = new ByteArray(payload, index, index + longOctetSize);
                    index += longOctetSize;
                    break;
                case DataType.SECURITY_KEY:
                    byte[] keyBytes = new byte[16];
                    Array.Copy(payload, index, keyBytes, 0, 16);
                    value[0] = new ZigBeeKey(keyBytes);
                    index += 16;
                    break;
                case DataType.ENDPOINT:
                case DataType.BITMAP_8_BIT:
                case DataType.DATA_8_BIT:
                case DataType.ENUMERATION_8_BIT:
                    value[0] = (byte)((byte)payload[index++] & 0xFF);
                    break;
                case DataType.EXTENDED_PANID:
                    byte[] panId = new byte[8];
                    for (int iCnt = 7; iCnt >= 0; iCnt--)
                    {
                        panId[iCnt] = payload[index + iCnt];
                    }
                    index += 8;
                    value[0] = new ExtendedPanId(panId);
                    break;
                case DataType.IEEE_ADDRESS:
                    byte[] address = new byte[8];
                    for (int iCnt = 7; iCnt >= 0; iCnt--)
                    {
                        address[iCnt] = payload[index + iCnt];
                    }
                    index += 8;
                    value[0] = new IeeeAddress(address);
                    break;
                case DataType.N_X_ATTRIBUTE_INFORMATION:
                    break;
                case DataType.N_X_ATTRIBUTE_RECORD:
                    break;
                case DataType.N_X_ATTRIBUTE_REPORT:
                    break;
                case DataType.N_X_ATTRIBUTE_REPORTING_CONFIGURATION_RECORD:
                    break;
                case DataType.N_X_ATTRIBUTE_SELECTOR:
                    break;
                case DataType.N_X_ATTRIBUTE_STATUS_RECORD:
                    break;
                case DataType.N_X_EXTENSION_FIELD_SET:
                    break;
                case DataType.N_X_NEIGHBORS_INFORMATION:
                    break;
                case DataType.N_X_READ_ATTRIBUTE_STATUS_RECORD:
                    List<ReadAttributeStatusRecord> records = new List<ReadAttributeStatusRecord>();

                    while (IsEndOfStream() == false)
                    {
                        ReadAttributeStatusRecord statusRecord = new ReadAttributeStatusRecord();
                        statusRecord.Deserialize(this);

                        records.Add(statusRecord);
                    }
                    value[0] = records;
                    break;
                case DataType.N_X_UNSIGNED_16_BIT_INTEGER:
                    try
                    {
                        int cntN16 = (byte)(payload[index++] & 0xFF);
                        List<ushort> arrayN16 = new List<ushort>(cntN16);
                        for (int arrayIndex = 0; arrayIndex < cntN16; arrayIndex++)
                        {
                            arrayN16.Add(BitConverter.ToUInt16(payload, index));

                            index += 2;
                        }
                        value[0] = arrayN16;
                    } catch (Exception ex)
                    {
                        string sTest = ex.Message;
                    }
                    break;
                case DataType.N_X_UNSIGNED_8_BIT_INTEGER:
                    int cntN8 = (byte)(payload[index++] & 0xFF);
                    List<byte> arrayN8 = new List<byte>(cntN8);
                    for (int arrayIndex = 0; arrayIndex < cntN8; arrayIndex++)
                    {
                        arrayN8.Add(payload[index++]);
                    }
                    value[0] = arrayN8;
                    break;
                case DataType.X_UNSIGNED_8_BIT_INTEGER:
                    int cntX8 = payload.Length - index;
                    List<byte> arrayX8 = new List<byte>(cntX8);
                    for (int arrayIndex = 0; arrayIndex < cntX8; arrayIndex++)
                    {
                        arrayX8.Add((byte)(payload[index++]));
                    }
                    value[0] = arrayX8;
                    break;
                case DataType.N_X_ATTRIBUTE_IDENTIFIER:
                    int cntX16 = (payload.Length - index) / 2;
                    List<ushort> arrayX16 = new List<ushort>(cntX16);
                    for (int arrayIndex = 0; arrayIndex < cntX16; arrayIndex++)
                    {
                        arrayX16.Add(BitConverter.ToUInt16(payload, index));

                        index += 2;
                    }
                    value[0] = arrayX16;
                    break;
                case DataType.UNSIGNED_8_BIT_INTEGER_ARRAY:
                    int cnt8Array = payload.Length - index;
                    byte[] intarray8 = new byte[cnt8Array];
                    for (int arrayIndex = 0; arrayIndex < cnt8Array; arrayIndex++)
                    {
                        intarray8[arrayIndex] = payload[index++];
                    }
                    value[0] = intarray8;
                    break;
                case DataType.N_X_WRITE_ATTRIBUTE_RECORD:
                    break;
                case DataType.N_X_WRITE_ATTRIBUTE_STATUS_RECORD:
                    break;
                case DataType.SIGNED_16_BIT_INTEGER:
                    short s = (short)(payload[index++] | (payload[index++] << 8));

                    value[0] = s;
                    break;
                case DataType.CLUSTERID:
                case DataType.NWK_ADDRESS:
                case DataType.BITMAP_16_BIT:
                case DataType.ENUMERATION_16_BIT:
                case DataType.UNSIGNED_16_BIT_INTEGER:
                    ushort us = (ushort)(payload[index++] | (payload[index++] << 8));

                    value[0] = us;
                    break;
                case DataType.BITMAP_24_BIT:
                case DataType.UNSIGNED_24_BIT_INTEGER:
                    value[0] = (uint)(payload[index++] + (payload[index++] << 8) | (payload[index++] << 16));
                    break;
                case DataType.SIGNED_24_BIT_INTEGER:
                    value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16);
                    break;
                case DataType.BITMAP_32_BIT:
                case DataType.UNSIGNED_32_BIT_INTEGER:
                case DataType.ENUMERATION_32_BIT:
                    value[0] = (uint)(payload[index++] + (payload[index++] << 8) | (payload[index++] << 16)
                            + (payload[index++] << 24));
                    break;
                case DataType.SIGNED_32_BIT_INTEGER:
                    value[0] = payload[index++] + (payload[index++] << 8) | (payload[index++] << 16)
                            + (payload[index++] << 24);
                    break;
                case DataType.UNSIGNED_40_BIT_INTEGER:
                    value[0] = (payload[index++]) + ((long)(payload[index++]) << 8) | ((long)(payload[index++]) << 16)
                            + ((long)(payload[index++]) << 24) | ((long)(payload[index++]) << 32);
                    break;

                case DataType.UNSIGNED_48_BIT_INTEGER:
                    value[0] = (payload[index++]) + ((long)(payload[index++]) << 8) | ((long)(payload[index++]) << 16)
                            + ((long)(payload[index++]) << 24) | ((long)(payload[index++]) << 32)
                            + ((long)(payload[index++]) << 40);
                    break;
                case DataType.SIGNED_8_BIT_INTEGER:
                    value[0] = (sbyte)(payload[index++]);
                    break;
                case DataType.UNSIGNED_8_BIT_INTEGER:
                    value[0] = (byte)(payload[index++] & 0xFF);
                    break;
                case DataType.UTCTIME:
                    //TODO: Implement date deserialization
                    break;
                case DataType.ROUTING_TABLE:
                    RoutingTable routingTable = new RoutingTable();
                    routingTable.Deserialize(this);
                    value[0] = routingTable;
                    break;
                case DataType.NEIGHBOR_TABLE:
                    NeighborTable neighborTable = new NeighborTable();
                    neighborTable.Deserialize(this);
                    value[0] = neighborTable;
                    break;
                case DataType.NODE_DESCRIPTOR:
                    NodeDescriptor nodeDescriptor = new NodeDescriptor();
                    nodeDescriptor.Deserialize(this);
                    value[0] = nodeDescriptor;
                    break;
                case DataType.POWER_DESCRIPTOR:
                    PowerDescriptor powerDescriptor = new PowerDescriptor();
                    powerDescriptor.Deserialize(this);
                    value[0] = powerDescriptor;
                    break;
                case DataType.BINDING_TABLE:
                    BindingTable bindingTable = new BindingTable();
                    bindingTable.Deserialize(this);
                    value[0] = bindingTable;
                    break;
                case DataType.SIMPLE_DESCRIPTOR:
                    SimpleDescriptor simpleDescriptor = new SimpleDescriptor();
                    simpleDescriptor.Deserialize(this);
                    value[0] = simpleDescriptor;
                    break;
                case DataType.ZCL_STATUS:
                    value[0] = (ZclStatus)(payload[index++]);
                    break;
                case DataType.ZDO_STATUS:
                    value[0] = (ZdoStatus)(payload[index++]);
                    break;
                case DataType.ZIGBEE_DATA_TYPE:
                    value[0] = ZclDataType.Get(payload[index++]);
                    break;
                case DataType.BYTE_ARRAY:
                    int cntB8 = (byte)(payload[index++] & 0xFF);
                    byte[] arrayB8 = new byte[cntB8];
                    for (int arrayIndex = 0; arrayIndex < cntB8; arrayIndex++)
                    {
                        arrayB8[arrayIndex] = (byte)(payload[index++] & 0xff);
                    }
                    value[0] = new ByteArray(arrayB8);
                    break;
                case DataType.FLOAT_32_BIT:
                    int val = payload[index++] + (payload[index++] << 8) + (payload[index++] << 16) + (payload[index++] << 24);
                    byte[] valBytes = BitConverter.GetBytes(val);
                    value[0] = BitConverter.ToSingle(valBytes, 0);
                    break;
                default:
                    throw new ArgumentException("No reader defined in " + this.GetType().Name + " for " + type.ToString() + " (" + (byte)type + ")");
            }
            return (T)value[0];
        }

19 Source : EndDeviceBindRequest.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            base.Deserialize(deserializer);

            // Create lists
            InClusterList = new List<ushort>();
            OutClusterList = new List<ushort>();

            BindingTarget = deserializer.Deserialize<ushort>(DataType.NWK_ADDRESS);
            SrcAddress = deserializer.Deserialize<IeeeAddress>(DataType.IEEE_ADDRESS);
            SrcEndpoint = deserializer.Deserialize<byte>(DataType.UNSIGNED_8_BIT_INTEGER);
            ProfileId = deserializer.Deserialize<ushort>(DataType.UNSIGNED_16_BIT_INTEGER);
            byte? inClusterCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (inClusterCount != null)
            {
                for (int cnt = 0; cnt < inClusterCount; cnt++)
                {
                    InClusterList.Add((ushort) deserializer.Deserialize(DataType.CLUSTERID));
                }
            }
            byte? outClusterCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (outClusterCount != null)
            {
                for (int cnt = 0; cnt < outClusterCount; cnt++)
                {
                    OutClusterList.Add((ushort) deserializer.Deserialize(DataType.CLUSTERID));
                }
            }
        }

19 Source : IeeeAddressResponse.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            base.Deserialize(deserializer);

            // Create lists
            NwkAddrreplacedocDevList = new List<ushort>();

            Status = deserializer.Deserialize<ZdoStatus>(DataType.ZDO_STATUS);
            if (Status != ZdoStatus.SUCCESS)
            {
                // Don't read the full response if we have an error
                return;
            }
            IeeeAddrRemoteDev = deserializer.Deserialize<IeeeAddress>(DataType.IEEE_ADDRESS);
            NwkAddrRemoteDev = deserializer.Deserialize<ushort>(DataType.NWK_ADDRESS);
            if (deserializer.IsEndOfStream)
            {
                return;
            }
            byte? numreplacedocDev = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            StartIndex = deserializer.Deserialize<byte>(DataType.UNSIGNED_8_BIT_INTEGER);
            if (numreplacedocDev != null)
            {
                for (int cnt = 0; cnt < numreplacedocDev; cnt++)
                {
                    NwkAddrreplacedocDevList.Add((ushort) deserializer.Deserialize(DataType.NWK_ADDRESS));
                }
            }
        }

19 Source : MatchDescriptorRequest.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            base.Deserialize(deserializer);

            // Create lists
            InClusterList = new List<ushort>();
            OutClusterList = new List<ushort>();

            NwkAddrOfInterest = deserializer.Deserialize<ushort>(DataType.NWK_ADDRESS);
            ProfileId = deserializer.Deserialize<ushort>(DataType.UNSIGNED_16_BIT_INTEGER);
            byte? inClusterCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (inClusterCount != null)
            {
                for (int cnt = 0; cnt < inClusterCount; cnt++)
                {
                    InClusterList.Add((ushort) deserializer.Deserialize(DataType.CLUSTERID));
                }
            }
            byte? outClusterCount = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            if (outClusterCount != null)
            {
                for (int cnt = 0; cnt < outClusterCount; cnt++)
                {
                    OutClusterList.Add((ushort) deserializer.Deserialize(DataType.CLUSTERID));
                }
            }
        }

19 Source : NetworkAddressResponse.cs
with Eclipse Public License 1.0
from Mr-Markus

internal override void Deserialize(ZclFieldDeserializer deserializer)
        {
            base.Deserialize(deserializer);

            // Create lists
            NwkAddrreplacedocDevList = new List<ushort>();

            Status = deserializer.Deserialize<ZdoStatus>(DataType.ZDO_STATUS);
            if (Status != ZdoStatus.SUCCESS)
            {
                // Don't read the full response if we have an error
                return;
            }
            IeeeAddrRemoteDev = deserializer.Deserialize<IeeeAddress>(DataType.IEEE_ADDRESS);
            NwkAddrRemoteDev = deserializer.Deserialize<ushort>(DataType.NWK_ADDRESS);
            byte? numreplacedocDev = (byte?) deserializer.Deserialize(DataType.UNSIGNED_8_BIT_INTEGER);
            StartIndex = deserializer.Deserialize<byte>(DataType.UNSIGNED_8_BIT_INTEGER);
            if (numreplacedocDev != null)
            {
                for (int cnt = 0; cnt < numreplacedocDev; cnt++)
                {
                    NwkAddrreplacedocDevList.Add((ushort) deserializer.Deserialize(DataType.NWK_ADDRESS));
                }
            }
        }

19 Source : CommandInterfaceImpl.cs
with Eclipse Public License 1.0
from Mr-Markus

private void CleanExpiredSynchronousCommandListeners()
        {
            long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            List<ushort> expired = new List<ushort>();
            lock (_synchronousCommandListeners)
            {
                var i = _synchronousCommandListeners.GetEnumerator();
                while (i.MoveNext())
                {
                    var entry = i.Current;
                    long expiration = _synchronousCommandListenerTimeouts[entry.Value];
                    if (expiration != -1L && expiration < now)
                    {
                        expired.Add(entry.Key);
                    }
                }

                foreach (ushort key in expired)
                {
                    _synchronousCommandListeners.Remove(key);
                }
                _commandListenerSync.Set();
            }
        }

19 Source : MeshUtils.cs
with GNU General Public License v3.0
from mrojkov

public static void RemoveDuplicates<TVertex>(Mesh<TVertex> mesh, IEqualityComparer<TVertex> comparer) where TVertex : unmanaged
		{
			var indexByVertexMap = new Dictionary<TVertex, ushort>(comparer);
			var vertices = new List<TVertex>();
			var indices = new List<ushort>();
			foreach (var i in mesh.Indices) {
				var v = mesh.Vertices[i];
				if (indexByVertexMap.TryGetValue(v, out var index)) {
					indices.Add(index);
				} else {
					index = checked((ushort)vertices.Count);
					vertices.Add(v);
					indices.Add(index);
					indexByVertexMap.Add(v, index);
				}
			}
			mesh.Vertices = vertices.ToArray();
			mesh.Indices = indices.ToArray();
			mesh.DirtyFlags |= MeshDirtyFlags.Vertices;
			mesh.DirtyFlags |= MeshDirtyFlags.Indices;
		}

19 Source : Machine.cs
with GNU General Public License v3.0
from Mwyann

public void FreeProcInstance(uint ptr)
        {
            if (ptr == 0)
                return;

            if (ptr.Hiword() != _systemCodeSelector)
            {
                Log.WriteLine("Invalid pointer preplaceded to FreeProcInstance: {0:X8}", ptr);
                return;
            }

            _freeProcInstances.Add(ptr.Loword());
        }

19 Source : LocalHeap.cs
with GNU General Public License v3.0
from Mwyann

ushort AllocHandle(ushort growSize)
        {
            // Do we have any free handles?
            if (_freeHandles.Count==0)
            {
                // No, allocate a fixed block of memory for the handles
                // Each handle in the block points to the actual location of the allocation elsewhere in the heap
                int handlesPerBlock = 32;

                // Allocate range
                var r = _allocator.Alloc(handlesPerBlock * 2, false, true);
                if (r == null)
                {
                    GrowHeap(handlesPerBlock * 2 + growSize + 1024);

                    r = _allocator.Alloc(handlesPerBlock * 2, false, true);
                    if (r == null)
                        return 0;
                }

                r.User = new LocalAllocation()
                {
                    flags = Win16.LMEM_FIXED,
                    handleOrPtr = 0,
                    range = r,
                };

                // Create handles
                for (int i=0; i<handlesPerBlock; i++)
                {
                    _freeHandles.Add((ushort)(r.Position + i * 2));
                }
            }

            // Remove from list
            ushort handle = _freeHandles[0];
            _freeHandles.RemoveAt(0);
            return handle;
        }

19 Source : CodeWindow.cs
with GNU General Public License v3.0
from Mwyann

public override void OnPaint(PaintContext ctx)
        {
            ctx.ClearLineOnReturn = true;

            // Setup disreplacedembler
            _dis.MemoryBus = _debugger.CPU.MemoryBus;
            _dis.cs = _topLineCS;
            _dis.ip = _topLineIP;

            /*
            // See if the current ip is already on screen
            if (_renderedCS == _caretCS)
            {
                int line = _renderedIPs.IndexOf(_caretIP);
                if (line>=0)
                {
                    if (line > ClientSize.Height - 3)
                    {
                        _dis.ip = _renderedIPs[line - (ClientSize.Height - 3)];
                    }
                    else
                    {
                        _dis.ip = _renderedIPs[0];
                    }
                }
            }


            */

            // Remember the current set of displayed instruction pointers
            _renderedCS = _dis.cs;
            _renderedIPs.Clear();


            for (int i=0; i<ClientSize.Height; i++)
            {
                ctx.Attributes = this.ClearAttributes;
                var bp = _debugger.FindCodeBreakPoint(_dis.cs, _dis.ip);
                if (bp != null && bp.Enabled)
                {
                    ctx.BackgroundColor = ConsoleColor.Red;
                    ctx.ForegroundColor = ConsoleColor.White;
                }

                string annot = "";
                char arrow;
                if (_dis.ip == _debugger.CPU.ip)
                {
                    ctx.BackgroundColor = ConsoleColor.Yellow;
                    ctx.ForegroundColor = ConsoleColor.Black;
                    arrow = '→';
                }
                else
                {
                    arrow = ' ';
                }

                _renderedIPs.Add(_dis.ip);

                var ipPos = _dis.ip;

                ctx.Write("{0:X4}:{1:X4} ", _dis.cs, _dis.ip);

                var asm = _dis.Read();

                if (ipPos == _debugger.CPU.ip)
                {
                    annot = _debugger.ExpressionContext.GenerateDisreplacedemblyAnnotations(asm, _dis.ImplicitParams);
                    if (!string.IsNullOrWhiteSpace(annot))
                    {
                        annot = "   ; " + annot;
                    }
                }

                    for (ushort b = 0; b<6; b++)
                {
                    if (ipPos + b < _dis.ip)
                    {
                        try
                        {
                            ctx.Write("{0:X2} ", _debugger.MemoryBus.ReadByte(_dis.cs, (ushort)(ipPos + b)));
                        }
                        catch (CPUException)
                        {
                            ctx.Write("?? ");
                        }
                    }
                    else
                    {
                        ctx.Write("   ");
                    }
                }

                ctx.WriteLine("{0} {1,3} {2} {3}", arrow, bp == null ? "" : ("#" + bp.Number.ToString()), asm, annot);
            }
        }

19 Source : CodeWindow.cs
with GNU General Public License v3.0
from Mwyann

ushort FindPriorIP(ushort cs, ushort ip, int instructions)
        {
            if (instructions == 0)
                return ip;

            ushort retryOffset = 0;
            var ips = new List<ushort>();


            retry:
            // Go back 4x number of instructions that we want to go back by
            var goBackBytes = 10 + (ushort)(instructions * 20);
            ushort dip;
            if (goBackBytes > ip)
                dip = 0;
            else
                dip = (ushort)(ip - goBackBytes);

            dip -= retryOffset;

            // Disreplacedamble from the address until we go past the current ip
            _dis.cs = cs;
            _dis.ip = dip;

            // Couldn't find a match
            if (_dis.ip == ip)
                return ip;

            // Build a list of ip addresses
            ips.Clear();
            while (_dis.ip < ip)
            {
                ips.Add(_dis.ip);
                _dis.Read();
            }

            // Did we hit it?
            if (_dis.ip != ip)
            {
                if (dip == 0)
                    return 0;
                retryOffset++;
                if (retryOffset < 10)
                    goto retry;
            }

            // Find the nth previous instruction
            return ips[ips.Count - instructions];
        }

19 Source : LocalHeap.cs
with GNU General Public License v3.0
from Mwyann

void FreeHandle(ushort handle)
        {
            if (handle!=0)
            {
                _freeHandles.Add(handle);
            }
        }

19 Source : SMD.cs
with GNU General Public License v3.0
from neodoso

public void ConvertModel()
        {
            vertices_list = new List<vertex>();
            triangles_list = new List<UInt16>();

            //List<string> test = new List<string>();

            int tri_counter = 0;

            //for each trianle in  SMD_triangles
            for (int t = 0; t < SMD_triangles.Count; t++)
            {
                bool vert_already_indexed = false;
                // for each vertex
                foreach (var vt in SMD_triangles[t].verts)
                {
                    vert_already_indexed = false;

                    // for each vertex
                    for (int v = 0; v < vertices_list.Count; v++)
                    {
                        // if the vertex is already indexed ni "vertices list", add vert index to triangles_list
                        if ((vt.pos.X == vertices_list[v].pos.X) && (vt.pos.Y == vertices_list[v].pos.Y) && (vt.pos.Z == vertices_list[v].pos.Z) && (vt.uv.X == vertices_list[v].uv.X))  //&& (vt.uv.Y == vertices_list[v].uv.Y)
                        {
                            vert_already_indexed = true;
                            triangles_list.Add((UInt16)v);
                            tri_counter++;
                            break;
                        }
                    }

                    // if vertex doesn't exist in "vertices_list" add it and also add vertex index in the triangles_list
                    if (!vert_already_indexed)
                    {
                        vertices_list.Add(vt);
                        triangles_list.Add((UInt16)(vertices_list.Count - 1));
                        tri_counter++;
                    }

                    #region store triangle material groups

                    // for every three vertices that make up a triangle
                    // store the triangle indices that are followed by the same material 
                    if (tri_counter == 3)
                    {
                        if (mat_groups_list.Count > 0)
                        {
                            // if material of current triangle is equal to previous mat_group triangle >> add triangl to the triangle/material list
                            if (mat_groups_list[mat_groups_list.Count - 1].material_name == SMD_triangles[t].mat_name)
                            {
                                mat_groups_list[mat_groups_list.Count - 1].triangle_count += 3;
                            }
                            else// if material of current triangle is not equal to previous mat_group triangle >> create and add new mat_group
                            {
                                mat_groups_list.Add(new material_group((UInt16)(triangles_list.Count - 3), 2, SMD_triangles[t].mat_name));
                                //mat_groups_list.Add(new material_group((UInt16)(triangles_list.Count), 2, SMD_triangles[t].mat_name));
                            }

                        } // if first triangle/mat_group 
                        else if (mat_groups_list.Count == 0)
                        {
                            mat_groups_list.Add(new material_group((UInt16)(triangles_list.Count - 3), 2, SMD_triangles[t].mat_name));
                        }
                        //reset triangle counter
                        tri_counter = 0;
                    }

                    #endregion
                }
            }

            flip_model();
        }

19 Source : IqmBuilder.cs
with MIT License
from NewBloodInteractive

void WriteAnimations(BinaryWriter writer, TextTable text, ref Header header)
        {
            // todo: make this code nicer

            if (FrameCount <= 0)
                return;

            header.PoseCount  = Bones.Count;
            header.FrameCount = FrameCount;
            var frameData     = new List<ushort>();
            var keyFrames     = new KeyFrame[Bones.Count];
            var channels      = new PoseChannels[FrameCount, Bones.Count];
            var poses         = new Pose[Bones.Count];

            for (int b = 0; b < Bones.Count; b++)
            {
                keyFrames[b] = new KeyFrame
                {
                    Bone      = Bones[b],
                    Translate = Bones[b].Translate,
                    Rotate    = Bones[b].Rotate,
                    Scale     = Bones[b].Scale
                };
            }

            for (int f = 0; f < FrameCount; f++)
            {
                if (frames.TryGetValue(f, out var keys))
                {
                    foreach (var key in keys)
                    {
                        var bone = Bones.IndexOf(key.Bone);
                        if (bone == -1) continue;
                        keyFrames[bone] = key;
                    }
                }

                for (int b = 0; b < Bones.Count; b++)
                {
                    var translate = CoordinateHelper.UnityToQuake(keyFrames[b].Translate);
                    var rotate    = CoordinateHelper.UnityToQuake(keyFrames[b].Rotate);
                    var scale     = CoordinateHelper.UnityToQuake(keyFrames[b].Scale, isScale: true);

                    channels[f, b][0] = translate.x;
                    channels[f, b][1] = translate.y;
                    channels[f, b][2] = translate.z;
                    channels[f, b][3] = rotate.x;
                    channels[f, b][4] = rotate.y;
                    channels[f, b][5] = rotate.z;
                    channels[f, b][6] = rotate.w;
                    channels[f, b][7] = scale.x;
                    channels[f, b][8] = scale.y;
                    channels[f, b][9] = scale.z;

                    for (int c = 0; c < 10; c++)
                    {
                        if (f == 0)
                            poses[b].Min[c] = poses[b].Max[c] = channels[f, b][c];
                        else
                        {
                            poses[b].Min[c] = Mathf.Min(poses[b].Min[c], channels[f, b][c]);
                            poses[b].Max[c] = Mathf.Max(poses[b].Max[c], channels[f, b][c]);
                        }
                    }
                }
            }

            for (int b = 0; b < Bones.Count; b++)
            {
                poses[b].Parent = Bones.IndexOf(Bones[b].Parent);

                for (int c = 0; c < 10; c++)
                {
                    poses[b].ChannelOffset[c] = poses[b].Min[c];
                    poses[b].ChannelScale [c] = 0;

                    if (poses[b].Min[c] == poses[b].Max[c])
                        continue;

                    poses[b].ChannelMask |= 1 << c;
                    poses[b].ChannelScale[c] = (poses[b].Max[c] - poses[b].Min[c]) / 65535f;
                    header.FrameChannelCount++;
                }
            }

            for (int f = 0; f < FrameCount; f++)
            {
                for (int b = 0; b < Bones.Count; b++)
                {
                    for (int c = 0; c < 10; c++)
                    {
                        if ((poses[b].ChannelMask & (1 << c)) == 0)
                            continue;

                        float frame = (channels[f, b][c] - poses[b].Min[c]) / (poses[b].Max[c] - poses[b].Min[c]);
                        frameData.Add((ushort)Mathf.Min(frame * 65535f, 65535f));
                    }
                }
            }

            header.PoseOffset = (int)writer.BaseStream.Position;
            foreach (var pose in poses) pose.Write(writer);

            header.FrameOffset = (int)writer.BaseStream.Position;
            foreach (var frame in frameData) writer.Write(frame);

            header.AnimCount  = Mathf.Max(1, Animations.Count);
            header.AnimOffset = (int)writer.BaseStream.Position;

            if (Animations.Count > 0)
            {
                foreach (var range in Animations)
                    WriteAnimation(range);
            }
            else
            {
                WriteAnimation(new AnimationRange
                {
                    Name       = "Sequence",
                    FrameCount = FrameCount,
                    FrameRate  = 24
                });
            }

            void WriteAnimation(AnimationRange range)
            {
                writer.Write(text.GetOrAddIndex(range.Name));
                writer.Write(range.FrameIndex);
                writer.Write(range.FrameCount);
                writer.Write(range.FrameRate);
                writer.Write((int)range.Flags);
            }
        }

19 Source : SetScaleKeysCommand.cs
with GNU Affero General Public License v3.0
from NexusForever

public void Read(GamePacketReader reader)
        {
            byte Count = reader.ReadByte();

            for (int i = 0; i < Count; i++)
                Times.Add(reader.ReadUInt());
                
            Type = reader.ReadByte(2u);
            Offset = reader.ReadUInt();
            Blend = reader.ReadBit();

            for (int i = 0; i < Count; i++)
                Scales.Add(reader.ReadUShort());

        }

19 Source : ClientRequestActionSetChanges.cs
with GNU Affero General Public License v3.0
from NexusForever

public void Read(GamePacketReader reader)
        {
            uint count = reader.ReadByte(4u);
            for (uint i = 0u; i < count; i++)
                Actions.Add(reader.ReadUInt());

            ActionSetIndex = reader.ReadByte(3u);

            count = reader.ReadByte(5u);            
            for (uint i = 0u; i < count; i++)
            {
                var actionTier = new ActionTier();
                actionTier.Read(reader);
                ActionTiers.Add(actionTier);
            }

            count = reader.ReadByte(7u);
            for (uint i = 0u; i < count; i++)
                Amps.Add(reader.ReadUShort());
        }

19 Source : Mocker.cs
with MIT License
from night-moon-studio

public static List<ushort> MockListUShort(int? len = null, bool notNull = false)
        {
            List<ushort> result = null;
            if (!notNull)
                if (random.Next(0, 10) == 5)
                    return result;

            result = new List<ushort>();
            len = len ?? random.Next(1, 100);
            for (int i = 0; i < len; i++)
                result.Add((ushort)(random.NextDouble() * ushort.MaxValue));

            return result;
        }

19 Source : WinHidDevice.ReportDescriptorReconstructor.cs
with MIT License
from OpenMacroBoard

void SetCollection(List<ushort> newNodes)
            {
                int countToCheck = Math.Min(_currentNodes.Count, newNodes.Count);
                int sharedCount;
                for (sharedCount = 0; sharedCount < countToCheck;  sharedCount++)
                {
                    if (_currentNodes[sharedCount] != newNodes[sharedCount]) { break; }
                }

                while (_currentNodes.Count > sharedCount)
                {
                    EndCollection(); _currentNodes.RemoveAt(_currentNodes.Count - 1);
                }

                for (int i = sharedCount; i < newNodes.Count; i++)
                {
                    ushort nodeIndex = newNodes[i]; _currentNodes.Add(nodeIndex); BeginCollection(nodeIndex);
                }
            }

19 Source : WinHidDevice.ReportDescriptorReconstructor.cs
with MIT License
from OpenMacroBoard

void SetCollection(ushort nodeIndex)
            {
                var nodes = _currentNodes;
                if (nodes.Count >= 1 && nodes[nodes.Count - 1] == nodeIndex) { return; }

                var newNodes = new List<ushort>();
                while (true)
                {
                    newNodes.Add(nodeIndex);
                    if (nodeIndex == 0) { break; }
                    nodeIndex = _nodes[nodeIndex].Parent;
                }
                newNodes.Reverse();

                SetCollection(newNodes);
            }

19 Source : RoadSegmentMesher.cs
with GNU Lesser General Public License v3.0
from OpenSAGE

protected void GenerateTriangles(int initialVertexCount, List<RoadShaderResources.RoadVertex> vertices, List<ushort> indices)
        {
            for (var i = initialVertexCount; i < vertices.Count - 2; i += 2)
            {
                indices.Add((ushort) (i + 0));
                indices.Add((ushort) (i + 1));
                indices.Add((ushort) (i + 3));

                indices.Add((ushort) (i + 0));
                indices.Add((ushort) (i + 2));
                indices.Add((ushort) (i + 3));
            }
        }

19 Source : YnvFile.cs
with GNU General Public License v2.0
from OwlGamingCommunity

private void BuildStructs()
        {
            Vector3 posoffset = Nav.SectorTree?.AABBMin.XYZ() ?? Vector3.Zero;
            Vector3 aabbsize = Nav.AABBSize;
            Vector3 aabbsizeinv = 1.0f / aabbsize;

            var vertlist = new List<NavMeshVertex>();
            var indslist = new List<ushort>();
            var edgelist = new List<NavMeshEdge>();
            var polylist = new List<NavMeshPoly>();
            var portallist = new List<NavMeshPortal>();
            var portallinks = new List<ushort>();

            var vertdict = new Dictionary<Vector3, ushort>();
            var areadict = new Dictionary<uint, uint>();
            var arealist = new List<uint>();
            var areaid = Nav.AreaID;
            EnsureEdgeAreaID(areaid, areadict, arealist);
            EnsureEdgeAreaID(0x3FFF, areadict, arealist);
            EnsureEdgeAreaID(areaid - 100, areadict, arealist);
            EnsureEdgeAreaID(areaid - 1, areadict, arealist);
            EnsureEdgeAreaID(areaid + 1, areadict, arealist);
            EnsureEdgeAreaID(areaid + 100, areadict, arealist);



            if (Polys != null) //rebuild vertices, indices, edges and polys lists from poly data.
            {
                for (int i = 0; i < Polys.Count; i++)
                {
                    var poly = Polys[i];
                    var vc = poly.Vertices?.Length ?? 0;
                    //poly.AreaID = (ushort)Nav.AreaID;
                    poly._RawData.IndexID = (ushort)indslist.Count;
                    for (int n = 0; n < vc; n++)
                    {
                        Vector3 v = poly.Vertices[n];
                        YnvEdge e = ((poly.Edges != null) && (n < poly.Edges.Length)) ? poly.Edges[n] : null;
                        ushort ind;
                        if (!vertdict.TryGetValue(v, out ind))
                        {
                            ind = (ushort)vertlist.Count;
                            vertdict[v] = ind;
                            vertlist.Add(NavMeshVertex.Create(Vector3.Clamp((v - posoffset) * aabbsizeinv, Vector3.Zero, Vector3.One)));
                        }
                        if ((poly.Indices != null) && (n < poly.Indices.Length))
                        {
                            poly.Indices[n] = ind;
                        }
                        indslist.Add(ind);

                        NavMeshEdge edge;
                        if (e != null)
                        {
                            if (e.Poly1 != null)
                            {
                                e.PolyID1 = (uint)e.Poly1.Index;
                                e.AreaID1 = e.Poly1.AreaID;
                                if (e.AreaID1 == 0x3FFF)
                                { }//debug
                            }
                            if (e.Poly2 != null)
                            {
                                e.PolyID2 = (uint)e.Poly2.Index;
                                e.AreaID2 = e.Poly2.AreaID;
                                if (e.AreaID2 == 0x3FFF)
                                { }//debug
                            }
                            if ((e.AreaID1 == 0) || (e.AreaID2 == 0))
                            { }//debug
                            e._RawData._Poly1.AreaIDInd = EnsureEdgeAreaID(e.AreaID1, areadict, arealist);
                            e._RawData._Poly2.AreaIDInd = EnsureEdgeAreaID(e.AreaID2, areadict, arealist);
                            edge = e.RawData;
                        }
                        else
                        {
                            var areaind = EnsureEdgeAreaID(0x3FFF, areadict, arealist);
                            edge = new NavMeshEdge();//create an empty edge
                            edge._Poly1.PolyID = 0x3FFF;
                            edge._Poly2.PolyID = 0x3FFF;
                            edge._Poly1.AreaIDInd = areaind;
                            edge._Poly2.AreaIDInd = areaind;
                        }
                        edgelist.Add(edge);
                    }
                    poly._RawData.IndexCount = vc;
                    poly._RawData.PortalLinkID = (uint)portallinks.Count;//these shouldn't be directly editable!
                    poly._RawData.PortalLinkCount = (byte)(poly.PortalLinks?.Length ?? 0);
                    if (poly.PortalLinks != null)
                    {
                        portallinks.AddRange(poly.PortalLinks);
                    }
                    poly.Index = i;//this should be redundant...
                    poly.CalculateAABB();//make sure this is up to date!
                    polylist.Add(poly.RawData);
                }
            }

            if (Portals != null)
            {
                for (int i = 0; i < Portals.Count; i++)
                {
                    var portal = Portals[i];
                    var pdata = portal.RawData;
                    pdata.PositionFrom = NavMeshVertex.Create((portal.PositionFrom - posoffset) * aabbsizeinv);
                    pdata.PositionTo = NavMeshVertex.Create((portal.PositionTo - posoffset) * aabbsizeinv);
                    portallist.Add(pdata);
                }
            }

            if (Points != null) //points will be built into the sector tree
            {
                for (int i = 0; i < Points.Count; i++)
                {
                    var point = Points[i];
                    var pdata = point.RawData;
                    pdata.Position = point.Position;
                }
            }


            if (Nav.Vertices == null)
            {
                Nav.Vertices = new NavMeshList<NavMeshVertex>();
                Nav.Vertices.VFT = 1080158456;
            }
            if (Nav.Indices == null)
            {
                Nav.Indices = new NavMeshList<ushort>();
                Nav.Indices.VFT = 1080158424;
            }
            if (Nav.Edges == null)
            {
                Nav.Edges = new NavMeshList<NavMeshEdge>();
                Nav.Edges.VFT = 1080158440;
            }
            if (Nav.Polys == null)
            {
                Nav.Polys = new NavMeshList<NavMeshPoly>();
                Nav.Polys.VFT = 1080158408;
            }


            Nav.Vertices.RebuildList(vertlist);
            Nav.VerticesCount = Nav.Vertices.ItemCount;

            Nav.Indices.RebuildList(indslist);

            Nav.Edges.RebuildList(edgelist);
            Nav.EdgesIndicesCount = Nav.Indices.ItemCount;

            Nav.Polys.RebuildList(polylist);
            Nav.PolysCount = Nav.Polys.ItemCount;

            Nav.Portals = (portallist.Count > 0) ? portallist.ToArray() : null;
            Nav.PortalsCount = (uint)(Nav.Portals?.Length ?? 0);
            Nav.PortalLinks = (portallinks.Count > 0) ? portallinks.ToArray() : null;
            Nav.PortalLinksCount = (uint)(Nav.PortalLinks?.Length ?? 0);

            var adjAreaIds = new NavMeshUintArray();
            adjAreaIds.Set(arealist.ToArray());
            Nav.AdjAreaIDs = adjAreaIds;


            for (int i = 0; i < Nav.Polys.ListParts.Count; i++) //rereplacedign part id's on all the polys...
            {
                var listpart = Nav.Polys.ListParts[i];
                var parreplacedems = listpart?.Items;
                if (parreplacedems == null) continue;
                ushort iu = (ushort)i;
                for (int j = 0; j < parreplacedems.Length; j++)
                {
                    parreplacedems[j].PartID = iu;
                }
            }



            //Build Sector Tree
            int depth = 0;
            if ((Nav.ContentFlags & NavMeshFlags.Vehicle) == 0) depth = 2;
            //vehicle navmesh has a single level, static has 3..

            NavMeshSector orig = Nav.SectorTree;
            NavMeshSector root = new NavMeshSector();
            root.SetAABBs(orig.AABBMin.XYZ(), orig.AABBMax.XYZ());

            uint pointindex = 0;

            BuildSectorTree(root, depth, ref pointindex);

            Nav.SectorTree = root;

        }

See More Examples