示例#1
0
        /// <summary>
        /// Process the filter on the specified image.
        /// </summary>
        ///
        /// <param name="image">Source image data.</param>
        /// <param name="rect">Image rectangle for processing by the filter.</param>
        ///
        protected override unsafe void ProcessFilter(UnmanagedImage image, Rectangle rect)
        {
            int pixelSize = Image.GetPixelFormatSize(image.PixelFormat) / 8;

            int startX = rect.Left;
            int startY = rect.Top;
            int stopX  = startX + rect.Width;
            int stopY  = startY + rect.Height;
            int stride = image.Stride;
            int offset = stride - rect.Width * pixelSize;

            // levels linear correction filter is going to be used on STEP 2
            LevelsLinear levelsLinear = new LevelsLinear( );

            // STEP 1 - search for min and max pixel values
            byte *ptr = (byte *)image.ImageData.ToPointer( );

            // check image format
            if (image.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                // allign pointer to the first pixel to process
                ptr += (startY * stride + startX);

                byte min = 255;
                byte max = 0;

                for (int y = startY; y < stopY; y++)
                {
                    for (int x = startX; x < stopX; x++, ptr++)
                    {
                        byte value = *ptr;

                        if (value < min)
                        {
                            min = value;
                        }

                        if (value > max)
                        {
                            max = value;
                        }
                    }
                    ptr += offset;
                }

                levelsLinear.InGray = new IntRange(min, max);
            }
            else
            {
                // allign pointer to the first pixel to process
                ptr += (startY * stride + startX * pixelSize);

                byte minR = 255, minG = 255, minB = 255;
                byte maxR = 0, maxG = 0, maxB = 0;

                for (int y = startY; y < stopY; y++)
                {
                    for (int x = startX; x < stopX; x++, ptr += pixelSize)
                    {
                        // red
                        byte value = ptr[RGB.R];

                        if (value < minR)
                        {
                            minR = value;
                        }

                        if (value > maxR)
                        {
                            maxR = value;
                        }

                        // green
                        value = ptr[RGB.G];

                        if (value < minG)
                        {
                            minG = value;
                        }

                        if (value > maxG)
                        {
                            maxG = value;
                        }

                        // blue
                        value = ptr[RGB.B];

                        if (value < minB)
                        {
                            minB = value;
                        }

                        if (value > maxB)
                        {
                            maxB = value;
                        }
                    }
                    ptr += offset;
                }

                levelsLinear.InRed   = new IntRange(minR, maxR);
                levelsLinear.InGreen = new IntRange(minG, maxG);
                levelsLinear.InBlue  = new IntRange(minB, maxB);
            }

            // STEP 2 - run levels linear correction
            levelsLinear.ApplyInPlace(image, rect);
        }
示例#2
0
        byte[] GetRGB(DepthImageFrame PImage, short[] depthFrame, DepthImageStream depthStream)
        {
            byte[] rgbs = new byte[PImage.Width * PImage.Height * 4];

            int nNear    = 999999;
            int nSavei32 = 0;
            int nTimer   = (int)(m_saveFrame % 150 / 30);

            // 각 영역의 좌표값 초기화
            for (int i = 0; i < partitionWidth; i++)
            {
                for (int j = 0; j < partitionHeight; j++)
                {
                    m_whichCell[i, j, 0] = int.MaxValue;
                    m_whichCell[i, j, 1] = int.MaxValue;
                    m_whichCell[i, j, 2] = int.MinValue;
                    m_whichCell[i, j, 3] = int.MinValue;
                    m_whichCell[i, j, 4] = int.MinValue;
                }
            }

            for (int i16 = 0, i32 = 0; i16 < depthFrame.Length && i32 < rgbs.Length; i16++, i32 += 4)
            {
                int nDistance = depthFrame[i16] >>
                                DepthImageFrame.PlayerIndexBitmaskWidth;

                int nX = i16 % PImage.Width;
                int nY = i16 / PImage.Width;

                int nCellX = (nX - 1) / (PImage.Width / partitionWidth);
                int nCellY = (nY - 1) / (PImage.Height / partitionHeight);

                // 화면이 나눠떨어지지 않는경우 예외처리
                if (nCellX >= partitionWidth)
                {
                    nCellX--;
                }

                if (nCellY >= partitionHeight)
                {
                    nCellY--;
                }

                if (nNear > nDistance && nDistance > 400)
                {
                    nNear    = nDistance;
                    nSavei32 = i32;
                }

                int nColor = 0xFF * nDistance / 4000;

                // 거리가 0~200 이라면 장애물로 판단,
                if (nDistance >= 0 && nDistance <= 200)
                {
                    // 해당 물체의 색을 red 로 처리하고 좌표값을 저장하는 함수와 장애물의 방향을 판단하는 함수를 호출한다.
                    SetRGB(rgbs, i32, 0xff, 0, 0);
                    SetCellObjCoordinate(nCellX, nCellY, nX, nY, nDistance);
                    CheckDirection(PImage, nCellX, nCellY, 0);
                }
                else
                {
                    SetRGB(rgbs, i32, (byte)nColor, (byte)nColor, (byte)nColor);
                }
            }

            SetRGB(rgbs, nSavei32, 0xFF, 0, 0);


            return(rgbs);
        }
示例#3
0
 /// <summary>
 /// Initialization constructor
 /// </summary>
 public TDSErrorToken(uint number, byte state, byte clazz, string message, string serverName) :
     this(number, state, clazz, message)
 {
     ServerName = serverName;
 }
示例#4
0
 public void Ctor_FamilyName_Size_Style_Unit_GdiCharSet_GdiVerticalFont(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
 {
     try
     {
         using (var font = new Font(fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont))
         {
             VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont);
         }
     }
     finally
     {
         fontFamily.Dispose();
     }
 }
示例#5
0
        private static void VerifyFont(Font font, string expectedName, float expectedEmSize, FontStyle expectedStyle, GraphicsUnit expectedUnit, byte expectedGdiCharset, bool expectedGdiVerticalFont)
        {
            Assert.Equal(expectedName, font.Name);
            Assert.Equal(expectedEmSize, font.Size);

            Assert.Equal(expectedStyle, font.Style);
            Assert.Equal((expectedStyle & FontStyle.Bold) != 0, font.Bold);
            Assert.Equal((expectedStyle & FontStyle.Italic) != 0, font.Italic);
            Assert.Equal((expectedStyle & FontStyle.Strikeout) != 0, font.Strikeout);
            Assert.Equal((expectedStyle & FontStyle.Underline) != 0, font.Underline);

            Assert.Equal(expectedUnit, font.Unit);
            Assert.Equal(expectedGdiCharset, font.GdiCharSet);
            Assert.Equal(expectedGdiVerticalFont, font.GdiVerticalFont);

            Assert.False(font.IsSystemFont);
            Assert.Empty(font.SystemFontName);
        }
示例#6
0
        public override async Task <GenericLoopbackConnection> EstablishGenericConnectionAsync()
        {
            Socket socket = await _listenSocket.AcceptAsync().ConfigureAwait(false);

            Stream stream = new NetworkStream(socket, ownsSocket: true);

            var options = new GenericLoopbackOptions()
            {
                Address       = _options.Address,
                SslProtocols  = _options.SslProtocols,
                UseSsl        = false,
                ListenBacklog = _options.ListenBacklog
            };

            GenericLoopbackConnection connection = null;

            try
            {
                if (_options.UseSsl)
                {
                    var sslStream = new SslStream(stream, false, delegate { return(true); });

                    using (X509Certificate2 cert = Configuration.Certificates.GetServerCertificate())
                    {
                        SslServerAuthenticationOptions sslOptions = new SslServerAuthenticationOptions();

                        sslOptions.EnabledSslProtocols  = _options.SslProtocols;
                        sslOptions.ApplicationProtocols = _options.SslApplicationProtocols;
                        sslOptions.ServerCertificate    = cert;

                        await sslStream.AuthenticateAsServerAsync(sslOptions, CancellationToken.None).ConfigureAwait(false);
                    }

                    stream = sslStream;
                    if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2)
                    {
                        // Do not pass original options so the CreateConnectionAsync won't try to do ALPN again.
                        return(connection = await Http2LoopbackServerFactory.Singleton.CreateConnectionAsync(socket, stream, options).ConfigureAwait(false));
                    }
                    if (sslStream.NegotiatedApplicationProtocol == SslApplicationProtocol.Http11 ||
                        sslStream.NegotiatedApplicationProtocol == default)
                    {
                        // Do not pass original options so the CreateConnectionAsync won't try to do ALPN again.
                        return(connection = await Http11LoopbackServerFactory.Singleton.CreateConnectionAsync(socket, stream, options).ConfigureAwait(false));
                    }
                    else
                    {
                        throw new Exception($"Unsupported negotiated protocol {sslStream.NegotiatedApplicationProtocol}");
                    }
                }

                if (_options.ClearTextVersion is null)
                {
                    throw new Exception($"HTTP server does not accept clear text connections, either set '{nameof(HttpAgnosticOptions.UseSsl)}' or set up '{nameof(HttpAgnosticOptions.ClearTextVersion)}' in server options.");
                }

                var buffer   = new byte[24];
                var position = 0;
                while (position < buffer.Length)
                {
                    var readBytes = await stream.ReadAsync(buffer, position, buffer.Length - position).ConfigureAwait(false);

                    if (readBytes == 0)
                    {
                        break;
                    }
                    position += readBytes;
                }

                var memory = new Memory <byte>(buffer, 0, position);
                stream = new ReturnBufferStream(stream, memory);

                var prefix = Text.Encoding.ASCII.GetString(memory.Span);
                if (prefix == Http2LoopbackConnection.Http2Prefix)
                {
                    if (_options.ClearTextVersion == HttpVersion.Version20 || _options.ClearTextVersion == HttpVersion.Unknown)
                    {
                        return(connection = await Http2LoopbackServerFactory.Singleton.CreateConnectionAsync(socket, stream, options).ConfigureAwait(false));
                    }
                }
                else
                {
                    if (_options.ClearTextVersion == HttpVersion.Version11 || _options.ClearTextVersion == HttpVersion.Unknown)
                    {
                        return(connection = await Http11LoopbackServerFactory.Singleton.CreateConnectionAsync(socket, stream, options).ConfigureAwait(false));
                    }
                }

                throw new Exception($"HTTP/{_options.ClearTextVersion} server cannot establish connection due to unexpected data: '{prefix}'");
            }
            catch
            {
                connection?.Dispose();
                connection = null;
                stream.Dispose();
                throw;
            }
            finally
            {
                if (connection != null)
                {
                    await connection.InitializeConnectionAsync().ConfigureAwait(false);
                }
            }
        }
		protected virtual DsaParameters GenerateParameters_FIPS186_3()
		{
			IDigest digest = this.digest;
			int num = digest.GetDigestSize() * 8;
			int n = this.N;
			byte[] array = new byte[n / 8];
			int num2 = (this.L - 1) / num;
			int n2 = (this.L - 1) % num;
			byte[] array2 = new byte[digest.GetDigestSize()];
			BigInteger bigInteger2;
			int i;
			BigInteger bigInteger7;
			while (true)
			{
				this.random.NextBytes(array);
				DsaParametersGenerator.Hash(digest, array, array2);
				BigInteger bigInteger = new BigInteger(1, array2).Mod(BigInteger.One.ShiftLeft(this.N - 1));
				bigInteger2 = BigInteger.One.ShiftLeft(this.N - 1).Add(bigInteger).Add(BigInteger.One).Subtract(bigInteger.Mod(BigInteger.Two));
				if (bigInteger2.IsProbablePrime(this.certainty))
				{
					byte[] array3 = Arrays.Clone(array);
					int num3 = 4 * this.L;
					for (i = 0; i < num3; i++)
					{
						BigInteger bigInteger3 = BigInteger.Zero;
						int j = 0;
						int num4 = 0;
						while (j <= num2)
						{
							DsaParametersGenerator.Inc(array3);
							DsaParametersGenerator.Hash(digest, array3, array2);
							BigInteger bigInteger4 = new BigInteger(1, array2);
							if (j == num2)
							{
								bigInteger4 = bigInteger4.Mod(BigInteger.One.ShiftLeft(n2));
							}
							bigInteger3 = bigInteger3.Add(bigInteger4.ShiftLeft(num4));
							j++;
							num4 += num;
						}
						BigInteger bigInteger5 = bigInteger3.Add(BigInteger.One.ShiftLeft(this.L - 1));
						BigInteger bigInteger6 = bigInteger5.Mod(bigInteger2.ShiftLeft(1));
						bigInteger7 = bigInteger5.Subtract(bigInteger6.Subtract(BigInteger.One));
						if (bigInteger7.BitLength == this.L && bigInteger7.IsProbablePrime(this.certainty))
						{
							goto Block_5;
						}
					}
				}
			}
			Block_5:
			if (this.usageIndex >= 0)
			{
				BigInteger bigInteger8 = this.CalculateGenerator_FIPS186_3_Verifiable(digest, bigInteger7, bigInteger2, array, this.usageIndex);
				if (bigInteger8 != null)
				{
					return new DsaParameters(bigInteger7, bigInteger2, bigInteger8, new DsaValidationParameters(array, i, this.usageIndex));
				}
			}
			BigInteger g = this.CalculateGenerator_FIPS186_3_Unverifiable(bigInteger7, bigInteger2, this.random);
			return new DsaParameters(bigInteger7, bigInteger2, g, new DsaValidationParameters(array, i));
		}
        private static MqttBasePacket DecodePublishPacket(byte header, IMqttPacketBodyReader body)
        {
            ThrowIfBodyIsEmpty(body);

            var retain = (header & 1) > 0;
            var qos    = (MqttQualityOfServiceLevel)(header >> 1 & 3);
            var dup    = (header >> 3 & 1) > 0;

            var packet = new MqttPublishPacket
            {
                Topic  = body.ReadStringWithLengthPrefix(),
                Retain = retain,
                QualityOfServiceLevel = qos,
                Dup = dup
            };

            if (qos > 0)
            {
                packet.PacketIdentifier = body.ReadTwoByteInteger();
            }

            var propertiesReader = new MqttV500PropertiesReader(body);

            while (propertiesReader.MoveNext())
            {
                if (packet.Properties == null)
                {
                    packet.Properties = new MqttPublishPacketProperties();
                }

                if (propertiesReader.CurrentPropertyId == MqttPropertyId.PayloadFormatIndicator)
                {
                    packet.Properties.PayloadFormatIndicator = propertiesReader.ReadPayloadFormatIndicator();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.MessageExpiryInterval)
                {
                    packet.Properties.MessageExpiryInterval = propertiesReader.ReadMessageExpiryInterval();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.TopicAlias)
                {
                    packet.Properties.TopicAlias = propertiesReader.ReadTopicAlias();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.ResponseTopic)
                {
                    packet.Properties.ResponseTopic = propertiesReader.ReadResponseTopic();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.CorrelationData)
                {
                    packet.Properties.CorrelationData = propertiesReader.ReadCorrelationData();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.SubscriptionIdentifier)
                {
                    if (packet.Properties.SubscriptionIdentifiers == null)
                    {
                        packet.Properties.SubscriptionIdentifiers = new List <uint>();
                    }

                    packet.Properties.SubscriptionIdentifiers.Add(propertiesReader.ReadSubscriptionIdentifier());
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.ContentType)
                {
                    packet.Properties.ContentType = propertiesReader.ReadContentType();
                }
                else if (propertiesReader.CurrentPropertyId == MqttPropertyId.UserProperty)
                {
                    if (packet.Properties.UserProperties == null)
                    {
                        packet.Properties.UserProperties = new List <MqttUserProperty>();
                    }

                    propertiesReader.AddUserPropertyTo(packet.Properties.UserProperties);
                }
                else
                {
                    propertiesReader.ThrowInvalidPropertyIdException(typeof(MqttPublishPacket));
                }
            }

            if (!body.EndOfStream)
            {
                packet.Payload = body.ReadRemainingData();
            }

            return(packet);
        }
示例#9
0
        //Bgra32とスケーリングしている場合は?ホットスポット?

        private BitmapSource MixBitmap(BitmapSource source, BitmapSource cursor, POINT cursorLocate, int xOffset, int yOffset)
        {
            BitmapSource resultBmp = null;
            int sideLenght = cursor.PixelWidth;//32、横一辺の長さ
            int maskHeight = cursor.PixelHeight;//64、縦は横の2倍のはず
            if (sideLenght * 2 != maskHeight) return resultBmp;//2倍じゃなければnullを返して終了

            //マスク画像を上下半分に切り出して画素値を配列化、マスク画像は白と黒の2色の1bpp画像のはず
            //ピクセルフォーマットをbgra32に変換して計算しやすくする
            BitmapSource maskBmp1 = new CroppedBitmap(cursor, new Int32Rect(0, 0, sideLenght, sideLenght));
            FormatConvertedBitmap m1 = new FormatConvertedBitmap(maskBmp1, PixelFormats.Bgra32, null, 0);
            //var m11 = new FormatConvertedBitmap(maskBmp1, PixelFormats.Bgr24, null, 0);
            int maskStride = (m1.PixelWidth * 32 + 7) / 8;
            byte[] mask1Pixels = new byte[m1.PixelHeight * maskStride];
            m1.CopyPixels(mask1Pixels, maskStride, 0);

            BitmapSource maskBmp2 = new CroppedBitmap(cursor, new Int32Rect(0, sideLenght, sideLenght, sideLenght));
            var m2 = new FormatConvertedBitmap(maskBmp2, PixelFormats.Bgra32, null, 0);
            byte[] mask2Pixels = new byte[m2.PixelHeight * maskStride];
            m2.CopyPixels(mask2Pixels, maskStride, 0);

            int w = source.PixelWidth;
            int h = source.PixelHeight;
            int bpp = source.Format.BitsPerPixel;//1ビクセルあたりのbit数、bgra32は4になるはず
            int stride = (w * bpp + 7) / 8;
            byte[] pixels = new byte[h * stride];
            source.CopyPixels(pixels, stride, 0);

            int beginX = cursorLocate.X - xOffset;
            int beginY = cursorLocate.Y - yOffset;
            int endX = beginX + sideLenght;
            int endY = beginY + sideLenght;
            if (endX > w) endX = w;
            if (endY > h) endY = h;

            int yCount = 0;
            int xCount = 0;
            int nekocount = 0;
            for (int y = beginY; y < endY; y++)
            {
                for (int x = beginX; x < endX; x++)
                {
                    var p = y * stride + x * 4;
                    var pp = yCount * maskStride + xCount * 4;
                    //pixels[p] = 0;
                    //pixels[p+1] = 0;
                    //pixels[p+2] = 0;


                    //マスク1が黒なら画像も黒にする
                    if (mask1Pixels[pp] == 0)
                    {
                        pixels[p] = 0;
                        pixels[p + 1] = 0;
                        pixels[p + 2] = 0;
                    }

                    //マスク2が白なら色反転
                    if (mask2Pixels[pp] == 255)
                    {
                        pixels[p] = (byte)(255 - pixels[p]);
                        pixels[p + 1] = (byte)(255 - pixels[p + 1]);
                        pixels[p + 2] = (byte)(255 - pixels[p + 2]);
                        nekocount++;
                    }
                    xCount++;
                }
                yCount++;
                xCount = 0;
            }

            return BitmapSource.Create(w, h, source.DpiX, source.DpiY, source.Format, source.Palette, pixels, stride);

        }
示例#10
0
        public void MergeTileChunks(YamlSequenceNode aChunks, YamlSequenceNode bChunks, YamlSequenceNode cChunks)
        {
            var aMap = ConvertTileChunks(aChunks);
            var bMap = ConvertTileChunks(bChunks);
            var cMap = ConvertTileChunks(cChunks);

            var xMap = new HashSet <string>();

            foreach (var kvp in aMap)
            {
                xMap.Add(kvp.Key);
            }
            // don't include b because that would mess with chunk deletion
            foreach (var kvp in cMap)
            {
                xMap.Add(kvp.Key);
            }

            foreach (var ind in xMap)
            {
                using var a  = new MemoryStream(GetChunkBytes(aMap, ind));
                using var b  = new MemoryStream(GetChunkBytes(bMap, ind));
                using var c  = new MemoryStream(GetChunkBytes(cMap, ind));
                using var aR = new BinaryReader(a);
                using var bR = new BinaryReader(b);
                using var cR = new BinaryReader(c);

                var outB = new byte[ExpectedChunkSize];

                {
                    using (var outS = new MemoryStream(outB))
                        using (var outW = new BinaryWriter(outS))

                            for (var i = 0; i < ExpectedChunkSize; i += 4)
                            {
                                var aI = aR.ReadUInt32();
                                var bI = MapTileId(bR.ReadUInt32(), TileMapFromBasedToOurs);
                                var cI = MapTileId(cR.ReadUInt32(), TileMapFromOtherToOurs);
                                // cI needs translation.

                                uint result = aI;
                                if (aI == bI)
                                {
                                    // If aI == bI then aI did not change anything, so cI always wins
                                    result = cI;
                                }
                                else if (bI != cI)
                                {
                                    // If bI != cI then cI definitely changed something (conflict, but overrides aI)
                                    result = cI;
                                    Console.WriteLine("WARNING: Tile (" + ind + ")[" + i + "] was changed by both branches.");
                                }
                                outW.Write(result);
                            }
                }

                // Actually output chunk
                if (!aMap.ContainsKey(ind))
                {
                    var res = new YamlMappingNode();
                    res.Children["ind"] = ind;
                    aMap[ind]           = res;
                }
                aMap[ind].Children["tiles"] = Convert.ToBase64String(outB);
            }
        }
示例#11
0
文件: Blob.cs 项目: xuzhe35/netmq
 public Blob Put(int pos, byte b)
 {
     m_buffer[pos] = b;
     m_hash = 0;
     return this;
 }
示例#12
0
 public void Write(byte value)
 {
     stream.WriteByte(value);
 }
示例#13
0
        public void readMapEndLDF()
        {
            //Load next file (-end)
            int    tIdx = 0;
            bool   nextTokenIsNumber;
            string wholeFile = File.ReadAllText(mapName.Replace("-pre.ldf", "-end.ldf"));
            int    nPos      = 0;

            findNextToken(wholeFile, ref nPos);

            initialViewportX = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            initialViewportY = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

            //	passabilityMask		byte[][]
            passabilityMask = new byte[mapWidth][];
            for (int y = 0; y < mapHeight; y++)
            {
                for (int x = 0; x < mapWidth; x++)
                {
                    if (y == 0)
                    {
                        passabilityMask[x] = new byte[mapHeight];
                    }
                    passabilityMask[x][y] = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                }
            }

            string nextType = readString(wholeFile, ref nPos); nextTokenIsNumber = findNextToken(wholeFile, ref nPos);

            while (nextType != "END")
            {
                if (nextType == "LEVELOBJ")
                {
                    if (levelObjects == null)
                    {
                        levelObjects = new LevelObj[0];
                    }
                    tIdx = levelObjects.Length;
                    Array.Resize(ref levelObjects, tIdx + 1);

                    //Have only found type = TERRAIN so far.
                    levelObjects[tIdx].type = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    //Some example names: PalmTree, PalmTree2, CrazyPalm
                    levelObjects[tIdx].name = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    levelObjects[tIdx].hp   = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    levelObjects[tIdx].x    = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    levelObjects[tIdx].y    = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                }
                else if (nextType == "RESERVEDLOC")
                {
                    if (reservedLocs == null)
                    {
                        reservedLocs = new ReservedLoc[0];
                    }
                    tIdx = reservedLocs.Length;
                    Array.Resize(ref reservedLocs, tIdx + 1);

                    reservedLocs[tIdx].initialFacing = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    reservedLocs[tIdx].x             = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    reservedLocs[tIdx].y             = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                }
                else if (nextType == "UNIT")
                {
                    if (units == null)
                    {
                        units = new Unit[0];
                    }
                    tIdx = units.Length;
                    Array.Resize(ref units, tIdx + 1);

                    if (nextTokenIsNumber) //Optional "SpecialAI" (1 = owned by player)
                    {
                        units[tIdx].specialAI = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
                    }
                    //May be BTREX, BUILDING, EGGS, DINO, GATHERER, HUNTER, SUPPLIES, or TNT
                    units[tIdx].type = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

                    //May be a lot of things, and it's in quotation marks. In the case of SUPPLIES, it's the name of an upgrade (like "carry2") that you get upon first taking from the pile.
                    units[tIdx].name = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

                    if (units[tIdx].type == "DINO") //Dinosaurs have a "rogue" flag
                    {
                        units[tIdx].rogue = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
                    }
                    if (units[tIdx].type != "BTREX" && units[tIdx].type != "TNT") //Baby T-Rex and TNT don't have HP
                    {
                        units[tIdx].hp = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    }
                    if (units[tIdx].type == "BUILDING") //Buildings have an ID instead of initialFacing
                    {
                        units[tIdx].ID = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    }
                    else if (units[tIdx].type != "BTREX") //Baby T-Rex doesn't have an ID or initialFacing here.
                    {
                        units[tIdx].initialFacing = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    }
                    units[tIdx].x = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    units[tIdx].y = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                }
                else if (nextType == "AIMARKER")
                {
                    if (aiMarkers == null)
                    {
                        aiMarkers = new AIMarker[0];
                    }
                    tIdx = aiMarkers.Length;
                    Array.Resize(ref aiMarkers, tIdx + 1);

                    //May be AIRDROP, DEFEND, GENSITE, GRAZE, HANGOUT, TRAIL, or PROXSENSOR
                    aiMarkers[tIdx].type = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    aiMarkers[tIdx].name = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    if (aiMarkers[tIdx].type != "GENSITE") //GENSITE doesn't have these three fields
                    {
                        aiMarkers[tIdx].radius = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                        if (aiMarkers[tIdx].type != "PROXSENSOR" && aiMarkers[tIdx].type != "AIRDROP") //PROXSENSOR and AIRDROP don't have the message field
                        {
                            aiMarkers[tIdx].message = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                        }
                        aiMarkers[tIdx].ID = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    }
                    aiMarkers[tIdx].x = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                    aiMarkers[tIdx].y = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
                }

                nextType = readString(wholeFile, ref nPos); nextTokenIsNumber = findNextToken(wholeFile, ref nPos);
            }
        }
示例#14
0
        //Process: open file. findNextToken. readString or readNumber, whichever you need.
        //If you need to check for an optional number like SpecialAI, check if ((getFrom[nPos] >= '0' && getFrom[nPos] <= '9') || getFrom[nPos] == '-')
        public void readMapPreLDF(string filename)
        {
            string wholeFile = "";
            int    nPos      = 0;

            mapName   = filename;
            wholeFile = File.ReadAllText(filename);

            findNextToken(wholeFile, ref nPos);
            initialPoints   = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            initialSupplies = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            resupplyThresh  = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            minGatherers    = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            maxGatherers    = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

            recruitAudio        = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            levelAudioSet       = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            cutSceneName        = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            missionBriefingName = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            levelAI             = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            nextLevel           = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            useTileset          = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
            backgroundTileset   = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            if (backgroundTileset != "" && !Path.HasExtension(backgroundTileset))
            {
                backgroundTileset += ".spr";
            }
            tileMapFile = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            if (tileMapFile != "" && !Path.HasExtension(tileMapFile))
            {
                tileMapFile += ".ldf";
            }

            mapWidth   = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            mapHeight  = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            background = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            if (background != "" && !Path.HasExtension(background))
            {
                background += ".spr";
            }
            paletteName = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            if (paletteName != "" && !Path.HasExtension(paletteName))
            {
                paletteName += ".pal";
            }
            objectives = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            if (objectives != "" && !Path.HasExtension(objectives))
            {
                objectives += ".spr";
            }
            objectivesAudio = readString(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

            //Gatherer available for selection at game start
            available = new bool[6];
            for (int x = 0; x < 6; x++)
            {
                available[x] = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
            }

            initialEggs = new byte[8];
            for (int x = 0; x < 8; x++)
            {
                initialEggs[x] = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }

            techTree = new bool[14];
            for (int x = 0; x < 14; x++)
            {
                techTree[x] = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
            }

            audioTracks = new bool[20];
            for (int x = 0; x < 20; x++)
            {
                audioTracks[x] = (readNumber(wholeFile, ref nPos) == 1); findNextToken(wholeFile, ref nPos);
            }

            m_bKillGatherer = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            m_bHuntDinos    = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            m_bHumanContact = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);

            //Rogue dino params (8 each)
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                rogueDinoResupplyThreshold[x] = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                rogueDinoCreationMax[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                rogueDinoCreationInitialDelay[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                rogueDinoCreationInterval[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }

            //Hunter params (5 each)
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 5; x++)
            {
                hunterResupplyThreshold[x] = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 5; x++)
            {
                hunterCreationMax[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 5; x++)
            {
                hunterCreationInitialDelay[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 5; x++)
            {
                hunterCreationInterval[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }

            //Hunter dino params (8 each)
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                hunterDinoResupplyThreshold[x] = (byte)readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                hunterDinoCreationMax[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                hunterDinoCreationInitialDelay[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
            if (nextTokenIsEnd(wholeFile, nPos))
            {
                return;
            }
            for (int x = 0; x < 8; x++)
            {
                hunterDinoCreationInterval[x] = readNumber(wholeFile, ref nPos); findNextToken(wholeFile, ref nPos);
            }
        }
 public ContactLookRequestByIdMessage(byte requestId, sbyte contactType, int playerId)
     : base(requestId, contactType)
 {
     this.playerId = playerId;
 }
示例#16
0
 public void SetPlayerLedState(PlayerLedState state)
 {
     flags2        |= Flags2.PlayerLed;
     ledPulseOption = 0x02;
     playerLedState = state.Value;
 }
示例#17
0
        public List<System.FileSystem.Listing.Base> GetRoot()
        {
            var xResult = new List<System.FileSystem.Listing.Base>();

            byte[] xData;
            if (FatType == FatTypeEnum.Fat32)
            {
                xData = NewClusterArray();
                ReadCluster(RootCluster, xData);
            }
            else
            {
                xData = mDevice.NewBlockArray(RootSectorCount);
                mDevice.ReadBlock(RootSector, RootSectorCount, xData);
            }
            //TODO: Change xLongName to StringBuilder
            string xLongName = "";
            for (UInt32 i = 0; i < xData.Length; i = i + 32)
            {
                byte xAttrib = xData[i + 11];
                if (xAttrib == Attribs.LongName)
                {
                    byte xType = xData[i + 12];
                    if (xType == 0)
                    {
                        byte xOrd = xData[i];
                        if ((xOrd & 0x40) > 0)
                        {
                            xLongName = "";
                        }
                        //TODO: Check LDIR_Ord for ordering and throw exception
                        // if entries are found out of order.
                        // Also save buffer and only copy name if a end Ord marker is found.
                        string xLongPart = xData.GetUtf16String(i + 1, 5);
                        // We have to check the length because 0xFFFF is a valid Unicode codepoint.
                        // So we only want to stop if the 0xFFFF is AFTER a 0x0000. We can determin
                        // this by also looking at the length. Since we short circuit the or, the length
                        // is rarely evaluated.
                        if (xData.ToUInt16(i + 14) != 0xFFFF || xLongPart.Length == 5)
                        {
                            xLongPart = xLongPart + xData.GetUtf16String(i + 14, 6);
                            if (xData.ToUInt16(i + 28) != 0xFFFF || xLongPart.Length == 11)
                            {
                                xLongPart = xLongPart + xData.GetUtf16String(i + 28, 2);
                            }
                        }
                        xLongName = xLongPart + xLongName;
                        //TODO: LDIR_Chksum 
                    }
                }
                else
                {
                    byte xStatus = xData[i];
                    if (xStatus == 0x00)
                    {
                        // Empty slot, and no more entries after this
                        break;
                    }
                    else if (xStatus == 0x05)
                    {
                        // Japanese characters - We dont handle these
                    }
                    else if (xStatus == 0xE5)
                    {
                        // Empty slot, skip it
                    }
                    else if (xStatus >= 0x20)
                    {
                        string xName;
                        if (xLongName.Length > 0)
                        {
                            // Leading and trailing spaces are to be ignored according to spec.
                            // Many programs (including Windows) pad trailing spaces although it 
                            // it is not required for long names.
                            // As per spec, ignore trailing periods
                            xName = xLongName.Trim();

                            //If there are trailing periods
                            int nameIndex = xName.Length - 1;
                            if (xName[nameIndex] == '.')
                            {
                                //Search backwards till we find the first non-period character
                                for (; nameIndex > 0; nameIndex--)
                                {
                                    if (xName[nameIndex] != '.')
                                    {
                                        break;
                                    }
                                }
                                //Substring to remove the periods
                                xName = xName.Substring(0, nameIndex + 1);
                            }
                        }
                        else
                        {
                            string xEntry = xData.GetAsciiString(i, 11);
                            xName = xEntry.Substring(0, 8).TrimEnd();
                            string xExt = xEntry.Substring(8, 3).TrimEnd();
                            if (xExt.Length > 0)
                            {
                                xName = xName + "." + xExt;
                            }
                        }

                        UInt32 xFirstCluster = (UInt32)(xData.ToUInt16(i + 20) << 16 | xData.ToUInt16(i + 26));

                        var xTest = xAttrib & (Attribs.Directory | Attribs.VolumeID);
                        if (xTest == 0)
                        {
                            UInt32 xSize = xData.ToUInt32(i + 28);
                            xResult.Add(new Listing.FatFile(this, xName, xSize, xFirstCluster));
                        }
                        else if (xTest == Attribs.VolumeID)
                        {
                            //
                        }
                        else if (xTest == Attribs.Directory)
                        {
                            xResult.Add(new Listing.FatDirectory(this, xName));
                        }
                        xLongName = "";
                    }
                }
            }

            return xResult;
        }
示例#18
0
 public void DisableLightBarAndPlayerLed()
 {
     ledFlags      |= LedFlags.LightBarFade;
     ledPulseOption = 0x01;
 }
示例#19
0
        }//sbmDownload end

        private void MakeFileList(String sbmfileName, List <SbmIssue> sbmIssue)
        {
            FileStream   fileStream   = new FileStream(@"C:\Dev\sbm\" + sbmfileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader binaryReader = new BinaryReader(fileStream);//, Encoding.UTF8);

            List <string> sbm = new List <string>();

            byte[] formatName    = binaryReader.ReadBytes(8); //"SMB-----"
            byte   version       = binaryReader.ReadByte();
            uint   meterialCount = binaryReader.ReadUInt16();
            uint   meshCount     = binaryReader.ReadUInt16();


            //byte[] meshBlock = binaryReader.ReadBytes((int)meshCount * (6));
            for (int i = 0; i < meterialCount; i++)
            {
                //byte[] meterialBlock =

                uint id = binaryReader.ReadUInt16();
                binaryReader.ReadBytes(((12 * 4) + 1));
                UInt16 stringLength = binaryReader.ReadUInt16();
                //이부분이 이름출력됨.

                if (stringLength < 5)
                {
                    continue;
                }

                char[] textureFileName = binaryReader.ReadChars(stringLength);
                // int testLet = binaryReader.PeekChar();

                //TODO : null 을 처리하려고 아래와 같은 조건을 썻으나 그냥 통과되어버림... 그냥 download 될 때 줘야 될 것 같음.

                sbm.Add(new string(textureFileName).Substring(5));
            }


            /************** 이하 부분은 아직 사용할 일이 없음--
             * /*
             * for (int i = 0; i < meshCount; i++)
             * {
             *  uint stringId = binaryReader.ReadUInt16();
             *  uint mat_id = binaryReader.ReadUInt16();
             *  uint vtCount = binaryReader.ReadUInt16();
             *  for (int j = 0; j < vtCount; j++)
             *  {
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *  }
             *  uint norCount = binaryReader.ReadUInt16(); // Normal Vector
             *  for (int j = 0; j < norCount; j++)
             *  {
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *  }
             *  uint tcCount = binaryReader.ReadUInt16();//Texture Coordinate
             *  for (int j = 0; j < tcCount; j++)
             *  {
             *      binaryReader.ReadSingle();
             *      binaryReader.ReadSingle();
             *  }
             *  uint idxCount = binaryReader.ReadUInt16();
             *  for (int j = 0; j < idxCount; j++)
             *  {
             *      binaryReader.ReadUInt16();
             *      binaryReader.ReadUInt16();
             *      binaryReader.ReadUInt16();
             *  }
             * }
             */

            binaryReader.Close();
            binaryReader.Dispose();

            fileStream.Close();
            //중복제거
            sbm = overlapCheck.CheckOverlap(sbm);
            TextureDownload(sbm, sbmIssue);
        }
示例#20
0
 public void SetMotorSpeeds(float lowFreq, float highFreq)
 {
     flags1 |= Flags1.MainMotors1 | Flags1.MainMotors2;
     lowFrequencyMotorSpeed  = (byte)Mathf.Clamp(lowFreq * 255, 0, 255);
     highFrequencyMotorSpeed = (byte)Mathf.Clamp(highFreq * 255, 0, 255);
 }
		protected virtual DsaParameters GenerateParameters_FIPS186_2()
		{
			byte[] array = new byte[20];
			byte[] array2 = new byte[20];
			byte[] array3 = new byte[20];
			byte[] array4 = new byte[20];
			int num = (this.L - 1) / 160;
			byte[] array5 = new byte[this.L / 8];
			if (!(this.digest is Sha1Digest))
			{
				throw new InvalidOperationException("can only use SHA-1 for generating FIPS 186-2 parameters");
			}
			BigInteger bigInteger;
			int i;
			BigInteger bigInteger4;
			while (true)
			{
				this.random.NextBytes(array);
				DsaParametersGenerator.Hash(this.digest, array, array2);
				Array.Copy(array, 0, array3, 0, array.Length);
				DsaParametersGenerator.Inc(array3);
				DsaParametersGenerator.Hash(this.digest, array3, array3);
				for (int num2 = 0; num2 != array4.Length; num2++)
				{
					array4[num2] = (array2[num2] ^ array3[num2]);
				}
				byte[] expr_B6_cp_0 = array4;
				int expr_B6_cp_1 = 0;
				expr_B6_cp_0[expr_B6_cp_1] |= 128;
				byte[] expr_D0_cp_0 = array4;
				int expr_D0_cp_1 = 19;
				expr_D0_cp_0[expr_D0_cp_1] |= 1;
				bigInteger = new BigInteger(1, array4);
				if (bigInteger.IsProbablePrime(this.certainty))
				{
					byte[] array6 = Arrays.Clone(array);
					DsaParametersGenerator.Inc(array6);
					for (i = 0; i < 4096; i++)
					{
						for (int j = 0; j < num; j++)
						{
							DsaParametersGenerator.Inc(array6);
							DsaParametersGenerator.Hash(this.digest, array6, array2);
							Array.Copy(array2, 0, array5, array5.Length - (j + 1) * array2.Length, array2.Length);
						}
						DsaParametersGenerator.Inc(array6);
						DsaParametersGenerator.Hash(this.digest, array6, array2);
						Array.Copy(array2, array2.Length - (array5.Length - num * array2.Length), array5, 0, array5.Length - num * array2.Length);
						byte[] expr_18F_cp_0 = array5;
						int expr_18F_cp_1 = 0;
						expr_18F_cp_0[expr_18F_cp_1] |= 128;
						BigInteger bigInteger2 = new BigInteger(1, array5);
						BigInteger bigInteger3 = bigInteger2.Mod(bigInteger.ShiftLeft(1));
						bigInteger4 = bigInteger2.Subtract(bigInteger3.Subtract(BigInteger.One));
						if (bigInteger4.BitLength == this.L && bigInteger4.IsProbablePrime(this.certainty))
						{
							goto Block_6;
						}
					}
				}
			}
			Block_6:
			BigInteger g = this.CalculateGenerator_FIPS186_2(bigInteger4, bigInteger, this.random);
			return new DsaParameters(bigInteger4, bigInteger, g, new DsaValidationParameters(array, i));
		}
 public override bool ContainsTag(byte token)
 {
     return true;
 }
示例#23
0
        public void FromLogFont_ValidLogFont_ReturnsExpected(FontStyle fontStyle, int weight, byte charSet)
        {
            // The boundary values of the weight that is considered Bold are different between Windows 7 and Windows 8.
            if (PlatformDetection.IsWindows7 || PlatformDetection.IsWindows8x)
            {
                return;
            }

            using (FontFamily family = FontFamily.GenericMonospace)
            {
                var logFont = new LOGFONT
                {
                    lfFaceName = family.Name,
                    lfWeight = weight,
                    lfItalic = (fontStyle & FontStyle.Italic) != 0 ? (byte)1 : (byte)0,
                    lfStrikeOut = (fontStyle & FontStyle.Strikeout) != 0 ? (byte)1 : (byte)0,
                    lfUnderline = (fontStyle & FontStyle.Underline) != 0 ? (byte)1 : (byte)0,
                    lfCharSet = charSet
                };
                using (Font font = Font.FromLogFont(logFont))
                {
                    VerifyFont(font, family.Name, font.Size, fontStyle, GraphicsUnit.World, charSet, expectedGdiVerticalFont: false);
                }
            }
        }
 public override Tag GetTag(byte token)
 {
     return new Tag(token, "Tag_" + token.ToString("X2"));
 }
示例#25
0
 void SetRGB(byte[] nPlayers, int nPos, byte r, byte g, byte b)
 {
     nPlayers[nPos + 2] = r;
     nPlayers[nPos + 1] = g;
     nPlayers[nPos + 0] = b;
 }
        private bool VerifyMftRecord(byte[] recordData, bool presentInBitmap, int bytesPerSector)
        {
            bool ok = true;

            //
            // Verify the attributes seem OK...
            //
            byte[] tempBuffer = new byte[recordData.Length];
            Array.Copy(recordData, tempBuffer, tempBuffer.Length);
            GenericFixupRecord genericRecord = new GenericFixupRecord(bytesPerSector);
            genericRecord.FromBytes(tempBuffer, 0);

            int pos = EndianUtilities.ToUInt16LittleEndian(genericRecord.Content, 0x14);
            while (EndianUtilities.ToUInt32LittleEndian(genericRecord.Content, pos) != 0xFFFFFFFF)
            {
                int attrLen;
                try
                {
                    AttributeRecord ar = AttributeRecord.FromBytes(genericRecord.Content, pos, out attrLen);
                    if (attrLen != ar.Size)
                    {
                        ReportError("Attribute size is different to calculated size.  AttrId={0}", ar.AttributeId);
                        ok = false;
                    }

                    if (ar.IsNonResident)
                    {
                        NonResidentAttributeRecord nrr = (NonResidentAttributeRecord)ar;
                        if (nrr.DataRuns.Count > 0)
                        {
                            long totalVcn = 0;
                            foreach (DataRun run in nrr.DataRuns)
                            {
                                totalVcn += run.RunLength;
                            }

                            if (totalVcn != nrr.LastVcn - nrr.StartVcn + 1)
                            {
                                ReportError("Declared VCNs doesn't match data runs.  AttrId={0}", ar.AttributeId);
                                ok = false;
                            }
                        }
                    }
                }
                catch
                {
                    ReportError("Failure parsing attribute at pos={0}", pos);
                    return false;
                }

                pos += attrLen;
            }

            //
            // Now consider record as a whole
            //
            FileRecord record = new FileRecord(bytesPerSector);
            record.FromBytes(recordData, 0);

            bool inUse = (record.Flags & FileRecordFlags.InUse) != 0;
            if (inUse != presentInBitmap)
            {
                ReportError("MFT bitmap and record in-use flag don't agree.  Mft={0}, Record={1}",
                    presentInBitmap ? "InUse" : "Free", inUse ? "InUse" : "Free");
                ok = false;
            }

            if (record.Size != record.RealSize)
            {
                ReportError("MFT record real size is different to calculated size.  Stored in MFT={0}, Calculated={1}",
                    record.RealSize, record.Size);
                ok = false;
            }

            if (EndianUtilities.ToUInt32LittleEndian(recordData, (int)record.RealSize - 8) != uint.MaxValue)
            {
                ReportError("MFT record is not correctly terminated with 0xFFFFFFFF");
                ok = false;
            }

            return ok;
        }
示例#27
0
        public static byte ReverseBits(byte value)
        {
            var reversed = (byte)(((((ulong)value * 0x80200802) & 0x884422110) * 0x101010101) >> 32);

            return(reversed);
        }
示例#28
0
        public void SaveAsPng(Stream stream, int width, int height)
        {
            // Get the Texture2D pixels
            byte[] data = new byte[Width * Height * 4];
            GetData(data);

            // Create an SDL_Surface*, write the pixel data
            IntPtr surface = SDL.SDL_CreateRGBSurface(
                0,
                Width,
                Height,
                32,
                0x000000FF,
                0x0000FF00,
                0x00FF0000,
                0xFF000000
                );

            SDL.SDL_LockSurface(surface);
            Marshal.Copy(
                data,
                0,
                INTERNAL_getSurfacePixels(surface),
                data.Length
                );
            SDL.SDL_UnlockSurface(surface);
            data = null;             // We're done with the original pixel data.

            // Blit to a scaled surface of the size we want, if needed.
            if (width != Width || height != Height)
            {
                IntPtr scaledSurface = SDL.SDL_CreateRGBSurface(
                    0,
                    width,
                    height,
                    32,
                    0x000000FF,
                    0x0000FF00,
                    0x00FF0000,
                    0xFF000000
                    );
                SDL.SDL_BlitScaled(
                    surface,
                    IntPtr.Zero,
                    scaledSurface,
                    IntPtr.Zero
                    );
                SDL.SDL_FreeSurface(surface);
                surface = scaledSurface;
            }

            // Create an SDL_RWops*, save PNG to RWops
            byte[] pngOut = new byte[width * height * 4];             // Max image size
            IntPtr dst    = SDL.SDL_RWFromMem(pngOut, pngOut.Length);

            SDL_image.IMG_SavePNG_RW(surface, dst, 1);
            SDL.SDL_FreeSurface(surface);             // We're done with the surface.

            // Get PNG size, write to Stream
            int size = (
                (pngOut[33] << 24) |
                (pngOut[34] << 16) |
                (pngOut[35] << 8) |
                (pngOut[36])
                ) + 41 + 57;         // 41 - header, 57 - footer

            stream.Write(pngOut, 0, size);
        }
示例#29
0
 /// <summary>
 /// Initialization constructor
 /// </summary>
 public TDSErrorToken(uint number, byte state, byte clazz, string message, string serverName, string procedureName) :
     this(number, state, clazz, message, serverName)
 {
     ProcedureName = procedureName;
 }
 /// <summary>
 /// sets the pixel value in the given byte array at location (x,y) with the given color to the given value.
 /// </summary>
 /// <param name="arr"></param>
 /// <param name="x"></param>
 /// <param name="y"></param>
 /// <param name="color"></param>
 /// <param name="toSet"></param>
 public void setPixel(byte[] arr, int x, int y, int color, byte toSet, SeamCarvingContext context)
 {
     int index = (int)context.Width * 4 * x + y * 4;
     arr[index + color] = toSet;
 }