Exemplo n.º 1
0
        public ShapesDemo(IntPtr hInstance)
            : base(hInstance) {
            _vb = null;
            _ib = null;
            _fx = null;
            _tech = null;
            _fxWVP = null;
            _inputLayout = null;
            _wireframeRS = null;
            _theta = 1.5f * MathF.PI;
            _phi = 0.1f * MathF.PI;
            _radius = 15.0f;

            MainWindowCaption = "Shapes Demo";

            _lastMousePos = new Point(0, 0);

            _gridWorld = Matrix.Identity;
            _view = Matrix.Identity;
            _proj = Matrix.Identity;

            _boxWorld = Matrix.Scaling(2.0f, 1.0f, 2.0f) * Matrix.Translation(0, 0.5f, 0);
            _centerSphere = Matrix.Scaling(2.0f, 2.0f, 2.0f) * Matrix.Translation(0, 2, 0);

            for (int i = 0; i < 5; ++i) {
                _cylWorld[i * 2] = Matrix.Translation(-5.0f, 1.5f, -10.0f + i * 5.0f);
                _cylWorld[i * 2 + 1] = Matrix.Translation(5.0f, 1.5f, -10.0f + i * 5.0f);

                _sphereWorld[i * 2] = Matrix.Translation(-5.0f, 3.5f, -10.0f + i * 5.0f);
                _sphereWorld[i * 2 + 1] = Matrix.Translation(5.0f, 3.5f, -10.0f + i * 5.0f);
            }

        }
Exemplo n.º 2
0
        /// <summary>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </summary>
        /// <remarks>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </remarks>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
        /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The buffer offset.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public int Read(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
#if false // Note: this code will never get called as we always use ReadResponse() instead.
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                ReadAhead(cancellationToken);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            inputIndex += n;

            return(n);
#else
            throw new NotImplementedException();
#endif
        }
Exemplo n.º 3
0
        public void InsertBytes(int offset, byte[] value, int valueOffset, int length)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (valueOffset < 0 || valueOffset >= value.Length)
            {
                throw new ArgumentOutOfRangeException("offset", "offset can not negative or >=data.Length");
            }
            if (length < 0 || valueOffset + length > value.Length)
            {
                throw new ArgumentOutOfRangeException("length", "length can not be negative or combined with offset longer than the array");
            }

            EnsureAdditionalCapacity(length);

            if (offset != this.position)
            {
                Buff.BlockCopy(this.buffer, offset, this.buffer, offset + length, this.position - offset);
            }

            Buff.BlockCopy(value, valueOffset, this.buffer, offset, length);
            this.position += length;
        }
Exemplo n.º 4
0
        protected override void DoInitialize()
        {
            {
                // particleSimulator-fountain.comp is also OK.
                var shaderCode = new ShaderCode(File.ReadAllText(@"shaders\ParticleSimulatorRenderer\particleSimulator.comp"), ShaderType.ComputeShader);
                this.computeProgram = shaderCode.CreateProgram();
            }
            {
                Buffer buffer = this.positionBuffer;
                Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.positionTexture = texture;
            }
            {
                Buffer buffer = this.velocityBuffer;
                Texture texture = buffer.DumpBufferTexture(OpenGL.GL_RGBA32F, autoDispose: false);
                texture.Initialize();
                this.velocityTexture = texture;
            }
            {
                const int length = 64;
                UniformBuffer buffer = UniformBuffer.Create(typeof(vec4), length, BufferUsage.DynamicCopy);
                buffer.Bind();
                OpenGL.BindBufferBase((BindBufferBaseTarget)BufferTarget.UniformBuffer, 0, buffer.BufferId);
                buffer.Unbind();
                this.attractorBuffer = buffer;

                OpenGL.CheckError();
            }
        }
Exemplo n.º 5
0
        public Minimap(Device device, DeviceContext dc, int minimapWidth, int minimapHeight, Terrain terrain, CameraBase viewCam) {
            _dc = dc;

            _minimapViewport = new Viewport(0, 0, minimapWidth, minimapHeight);

            CreateMinimapTextureViews(device, minimapWidth, minimapHeight);

            _terrain = terrain;

            SetupOrthoCamera();
            _viewCam = viewCam;

            // frustum vb will contain four corners of view frustum, with first vertex repeated as the last
            var vbd = new BufferDescription(
                VertexPC.Stride * 5,
                ResourceUsage.Dynamic,
                BindFlags.VertexBuffer,
                CpuAccessFlags.Write,
                ResourceOptionFlags.None,
                0
            );
            _frustumVB = new Buffer(device, vbd);

            _edgePlanes = new[] {
                new Plane(1, 0, 0, -_terrain.Width / 2),
                new Plane(-1, 0, 0, _terrain.Width / 2),
                new Plane(0, 1, 0, -_terrain.Depth / 2),
                new Plane(0, -1, 0, _terrain.Depth / 2)
            };

            ScreenPosition = new Vector2(0.25f, 0.75f);
            Size = new Vector2(0.25f, 0.25f);
        }
Exemplo n.º 6
0
		public static bool Insert(Buffer dest, Buffer source)
		{
			if (dest.BitsLeft() < source.BitsLeft())
				return false;

			Bitstream.Buffer tmp = new Bitstream.Buffer();
			Copy(tmp, source);

			while (tmp.BitsLeft() > 0)
			{
				if (tmp.bitpos > 0)
				{
					uint bits = (uint)(8 - tmp.bitpos);
					if (bits > tmp.BitsLeft())
					{
						bits = tmp.BitsLeft();
					}
					Bitstream.PutBits(dest, bits, Bitstream.ReadBits(tmp, bits));
				}
				if (tmp.BitsLeft() > 32)
					Bitstream.PutBits(dest, 32, Bitstream.ReadBits(tmp, 32));

				uint left = tmp.BitsLeft();
				if (left >= 8)
				{
					Bitstream.PutBits(dest, 8, Bitstream.ReadBits(tmp, 8));
				}
				else if (left > 0)
				{
					Bitstream.PutBits(dest, left, Bitstream.ReadBits(tmp, left));
				}
			}
			return true;
		}
Exemplo n.º 7
0
 private void Read_file(string filename, Action<Buffer> continueWith) {
     using (var fileStream = File.Open(filename, FileMode.Open, FileAccess.Read)) {
         var buffer = new Buffer();
         buffer.LengthUsed = fileStream.Read(buffer.Content, 0, buffer.Content.Length);
         continueWith(buffer);
     }
 }
Exemplo n.º 8
0
 private void ReadOne(Buffer buffer, LowLevelTcpConnection connection)
 {
     connection.ReadAsync(buffer.Segment.Array, buffer.Segment.Offset, buffer.Segment.Count,
         readBytes =>
             {
                 var readSegment = new ArraySegment<byte>(buffer.Segment.Array, 0, buffer.Segment.Offset + readBytes);
                 int headersSize;
                 var headers = TryParse(readSegment, out headersSize);
                 if (headers != null)
                 {
                     FixBuffer(buffer.Segment.Array, headersSize, buffer.Segment.Offset + readBytes);
                     StartHttp(headers, buffer.Segment.Array, connection);
                 }
                 else
                 {
                     ReadOne(new Buffer()
                                 {
                                     Segment =
                                         new ArraySegment<byte>(buffer.Segment.Array,
                                                                buffer.Segment.Offset + readBytes,
                                                                buffer.Segment.Count - readBytes),
                                 }, connection);
                 }
             });
 }
        public override void MakeBinary(string path)
        {
            ReadObj(path, out List <Vector3> outPositions, out List <Vector2> outTexCoords, out List <Vector3> outNormals, out List <VertexReference> outVertices);

            int vertexCount = outPositions.Count;

            byte[] closure = _closures[Name];
            Buffer = new byte[10 + vertexCount * Vertex.ByteCount + vertexCount * sizeof(uint) + closure.Length];

            Buf.BlockCopy(BitConverter.GetBytes((uint)vertexCount), 0, Buffer, 0, sizeof(uint));
            Buf.BlockCopy(BitConverter.GetBytes((uint)vertexCount), 0, Buffer, 4, sizeof(uint));
            Buf.BlockCopy(BitConverter.GetBytes((ushort)288), 0, Buffer, 8, sizeof(ushort));

            for (int i = 0; i < vertexCount; i++)
            {
                Vertex vertex      = new(outPositions[(int)outVertices[i].PositionReference - 1], outTexCoords[(int)outVertices[i].TexCoordReference - 1], outNormals[(int)outVertices[i].NormalReference - 1]);
                byte[] vertexBytes = vertex.ToByteArray();
                Buf.BlockCopy(vertexBytes, 0, Buffer, 10 + i * Vertex.ByteCount, Vertex.ByteCount);
            }

            for (int i = 0; i < vertexCount; i++)
            {
                Buf.BlockCopy(BitConverter.GetBytes(outVertices[i].PositionReference - 1), 0, Buffer, 10 + vertexCount * Vertex.ByteCount + i * sizeof(uint), sizeof(uint));
            }
            Buf.BlockCopy(closure, 0, Buffer, 10 + vertexCount * (Vertex.ByteCount + sizeof(uint)), closure.Length);

            Size = (uint)Buffer.Length;
        }
Exemplo n.º 10
0
 public MyModel(Project1Game game, VertexPositionColor[] shapeArray, String textureName)
 {
     this.vertices = Buffer.Vertex.New(game.GraphicsDevice, shapeArray);
     this.inputLayout = VertexInputLayout.New<VertexPositionColor>(0);
     vertexStride = Utilities.SizeOf<VertexPositionColor>();
     modelType = ModelType.Colored;
 }
Exemplo n.º 11
0
        async Task <int> ReadAsync(byte[] buffer, int offset, int count, bool doAsync, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (Mode != ImapStreamMode.Literal)
            {
                return(0);
            }

            count = Math.Min(count, literalDataLeft);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                await ReadAheadAsync(BlockSize, doAsync, cancellationToken).ConfigureAwait(false);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            literalDataLeft -= n;
            inputIndex      += n;

            if (literalDataLeft == 0)
            {
                Mode = ImapStreamMode.Token;
            }

            return(n);
        }
Exemplo n.º 12
0
 public BufferPool()
 {
     for (int i = 0; i < PoolSize; i++)
     {
         pool[i] = new Buffer(this, BufferLength);
     }
 }
Exemplo n.º 13
0
        public void UpdateBufferForBlock(int program, string nameBlock)
        {
            int index_SLI = GL.GetUniformBlockIndex(program, nameBlock);

            if (index_SLI != -1)
            {
                GL.GetActiveUniformBlock(program, index_SLI, ActiveUniformBlockParameter.UniformBlockDataSize, out blockSizeLightInfo);
                byte[]   blockBuffer = new byte[blockSizeLightInfo];
                string[] names       = { nameBlock + ".position_lgh", nameBlock + ".intensity_lgh", nameBlock + ".direction_lgh", nameBlock + ".exponent_lgh", nameBlock + ".cutoff_lgh" };
                int[]    indices     = new int[5];
                GL.GetUniformIndices(program, 5, names, indices);
                int[] offset = new int[5];
                GL.GetActiveUniforms(program, 5, indices, ActiveUniformParameter.UniformOffset, offset);

                float[] position_lgh  = { Position.X, Position.Y, Position.Z, 0.0f };
                float[] intensity_lgh = { DiffusionIntensity.X, DiffusionIntensity.Y, DiffusionIntensity.Z }; //интенсивность света
                float[] direction_lgh = { LightVecNormalized.X, LightVecNormalized.Y, LightVecNormalized.Z }; //направление света
                float[] exponent      = { 1.0f };                                                             // Экспанента углового ослабления света
                float[] cutoff        = { 30f };                                                              //угол отсечения

                Buffer.BlockCopy(position_lgh, 0, blockBuffer, offset[0], position_lgh.Length * sizeof(float));
                Buffer.BlockCopy(intensity_lgh, 0, blockBuffer, offset[1], intensity_lgh.Length * sizeof(float));
                Buffer.BlockCopy(direction_lgh, 0, blockBuffer, offset[2], direction_lgh.Length * sizeof(float));
                Buffer.BlockCopy(exponent, 0, blockBuffer, offset[3], exponent.Length * sizeof(float));
                Buffer.BlockCopy(cutoff, 0, blockBuffer, offset[4], cutoff.Length * sizeof(float));

                GL.BindBuffer(BufferTarget.UniformBuffer, uboLightInfo);
                GL.BufferSubData(BufferTarget.UniformBuffer, (IntPtr)0, blockSizeLightInfo, blockBuffer);
            }
        }
Exemplo n.º 14
0
        public byte[] ToArray()
        {
            byte[] value = new byte[Length];
            Buff.BlockCopy(this.buffer, 0, value, 0, Length);

            return(value);
        }
Exemplo n.º 15
0
        public void WriteDouble(double value)
        {
            if (this.position + sizeof(double) >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + sizeof(double))
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

                        #if SAFE
            Buff.BlockCopy(BitConverter.GetBytes(value), 0, this.buffer, this.position, sizeof(double));
                        #else
            fixed(byte *ub = this.buffer)
            * ((double *)(ub + this.position)) = value;
                        #endif

            this.position += sizeof(double);
        }
Exemplo n.º 16
0
			public static Buffer Make(byte[] buffer)
			{
				Buffer b = new Buffer();
				b.buf = buffer;
				b.bytesize = (uint)buffer.Length;
				return b;
			}
Exemplo n.º 17
0
        public SegmentRenderer()
        {
            m_program = TriangleProgram.Instance;
            m_instances = new List<SegmentInstance>();

            m_vao = new VertexArray();

            GL.BindVertexArray(m_vao);
            GL.UseProgram(m_program);

            m_bufferSprite = new Buffer<SegmentData>();
            m_bufferTriangle = new Buffer<Vector3>();

            m_program.Position.SetValue(m_bufferSprite.GetView<Vector3>("Position"));

            m_program.Color.SetValue(m_bufferSprite.GetView<Color4ub>("Color"));
            //m_program.Position.SetDivisor(1);
               // m_program.Normal.SetValue(m_bufferSprite.GetView<Vector3>("Normal"));
               //// m_program.Normal.SetDivisor(1);
               // m_program.Transform.SetValue(m_bufferSprite.GetView<Matrix4>("Transform"));
               // //m_program.Transform.SetDivisor(1);
               // m_program.TextureOrigin.SetValue(m_bufferSprite.GetView<Vector2>("TextureOrigin"));
               // //m_program.TextureOrigin.SetDivisor(1);
               // m_program.TextureTarget.SetValue(m_bufferSprite.GetView<Vector2>("TextureTarget"));
            //m_program.TextureTarget.SetDivisor(1);

            GL.BindVertexArray(null);

            m_isDirty = true;
        }
Exemplo n.º 18
0
        public void WriteBytes(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            int additionalCapacity = sizeof(int) + value.Length;

            if (this.position + additionalCapacity >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + additionalCapacity)
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

            Buff.BlockCopy(BitConverter.GetBytes(value.Length), 0, this.buffer, this.position, sizeof(int));
            this.position += sizeof(int);
            Buff.BlockCopy(value, 0, this.buffer, this.position, value.Length);
            this.position += value.Length;
        }
Exemplo n.º 19
0
        private void OnLoad(object sender, EventArgs e)
        {
            // initialize shader (load sources, create/compile/link shader program, error checking)
            // when using the factory method the shader sources are retrieved from the ShaderSourceAttributes
            _program = ProgramFactory.Create<ExampleProgram>();
            // this program will be used all the time so just activate it once and for all
            _program.Use();

            // create vertices for a triangle
            var vertices = new[] { new Vector3(-1,-1,0), new Vector3(1,-1,0), new Vector3(0,1,0) };

            // create buffer object and upload vertex data
            _vbo = new Buffer<Vector3>();
            _vbo.Init(BufferTarget.ArrayBuffer, vertices);

            // create and bind a vertex array
            _vao = new VertexArray();
            _vao.Bind();
            // set up binding of the shader variable to the buffer object
            _vao.BindAttribute(_program.InPosition, _vbo);

            // set camera position
            Camera.DefaultState.Position = new Vector3(0,0,3);
            Camera.ResetToDefault();

            // set a nice clear color
            GL.ClearColor(Color.MidnightBlue);
        }
Exemplo n.º 20
0
        public SpriteRenderer(SpriteSheet spriteSheet)
        {
            SpriteSheet = spriteSheet;

            m_program = SpriteProgram.Instance;
            m_instances = new List<SpriteInstance>();
            m_vao = new VertexArray();

            GL.BindVertexArray(m_vao);

            m_bufferSprite = new Buffer<SpriteData>();
            m_bufferQuad = new Buffer<Vector3>();

            m_bufferQuad.SetData(new Vector3[] {
                new Vector3(0f, 0f, 0f),
                new Vector3(0f, 1f, 0f),
                new Vector3(1f, 1f, 0f),
                new Vector3(1f, 0f, 0f)
            });

            GL.UseProgram(m_program);

            m_program.Position.SetValue(m_bufferQuad.GetView());

            m_program.Transform.SetValue(m_bufferSprite.GetView<Matrix4>("Transform"));
            m_program.Transform.SetDivisor(1);
            m_program.TextureOrigin.SetValue(m_bufferSprite.GetView<Vector2>("TextureOrigin"));
            m_program.TextureOrigin.SetDivisor(1);
            m_program.TextureTarget.SetValue(m_bufferSprite.GetView<Vector2>("TextureTarget"));
            m_program.TextureTarget.SetDivisor(1);

            GL.BindVertexArray(null);

            m_isDirty = true;
        }
Exemplo n.º 21
0
        /*
         * private static NDArray ReadTensorFromImageFile(Bitmap bmp)
         * {
         *  var graph = tf.Graph().as_default();
         *
         *  string file_name = @"E:\Download\faster_rcnn_resnet50_smd_2019_01_29\images\ships1.jpg";
         *  Tensor file_reader = tf.io.read_file(file_name, "file_reader");
         *  Tensor decodeFromFile = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
         *
         *  NDArray nd = bmp.ToNDArray(discardAlpha: true);
         *  nd.shape = new int[]{ 1, bmp.Height, bmp.Width, 3 };
         *  Tensor content = new Tensor(nd,TF_DataType.TF_UINT8);
         *  return nd;
         *  var decodeJpeg = tf.image.decode_image(content);
         *
         *  var casted = tf.cast(decodeJpeg, TF_DataType.TF_UINT8);
         *  var dims_expander = tf.expand_dims(casted, 0);
         *
         *  using (var sess = tf.Session(graph))
         *      return sess.run(dims_expander);
         * }
         */

        private static NDArray GetBitmapBytes(Bitmap image, out byte[] RawBytes)
        {
            // En garde!
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            BitmapData bmpData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);

            try
            {
                unsafe
                {
                    RawBytes = new byte[bmpData.Stride * image.Height];
                    //Create a 1d vector without filling it's values to zero (similar to np.empty)
                    var nd = new NDArray(NPTypeCode.Byte, Shape.Vector(bmpData.Stride * image.Height), fillZeros: false);

                    // Get the respective addresses
                    byte *src = (byte *)bmpData.Scan0;
                    byte *dst = (byte *)nd.Unsafe.Address; //we can use unsafe because we just allocated that array and we know for sure it is contagious.

                    Marshal.Copy(bmpData.Scan0, RawBytes, 0, RawBytes.Length);
                    // Copy the RGB values into the array.
                    Buffer.MemoryCopy(src, dst, nd.size, nd.size); //faster than Marshal.Copy
                    //TODO: replace return with: return nd.reshape(batch_size, height, width, 3);
                    return(nd);
                }
            }
            finally
            {
                image.UnlockBits(bmpData);
            }
        }
Exemplo n.º 22
0
        public ParticleSystem(GraphicsDevice device, ContentManager content)
        {
            this.device = device;

            // Create vertex buffer used to spawn new particles
            this.particleStart = Buffer.Vertex.New<ParticleVertex>(device, MAX_NEW);

            // Create vertex buffers to use for updating and drawing the particles alternatively
            var vbFlags = BufferFlags.VertexBuffer | BufferFlags.StreamOutput;
            this.particleDrawFrom = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);
            this.particleStreamTo = Buffer.New<ParticleVertex>(device, MAX_PARTICLES, vbFlags);

            this.layout = VertexInputLayout.FromBuffer(0, this.particleStreamTo);
            this.effect = content.Load<Effect>("ParticleEffect");
            this.texture = content.Load<Texture2D>("Dot");

            this.viewParameter = effect.Parameters["_view"];
            this.projParameter = effect.Parameters["_proj"];
            this.lookAtMatrixParameter = effect.Parameters["_lookAtMatrix"];
            this.elapsedSecondsParameter = effect.Parameters["_elapsedSeconds"];
            this.camDirParameter = effect.Parameters["_camDir"];
            this.gravityParameter = effect.Parameters["_gravity"];
            this.textureParameter = effect.Parameters["_texture"];
            this.samplerParameter = effect.Parameters["_sampler"];
            this.updatePass = effect.Techniques["UpdateTeq"].Passes[0];
            this.renderPass = effect.Techniques["RenderTeq"].Passes[0];
        }
Exemplo n.º 23
0
 public void Process(Buffer buffer) {
     if (first) {
         first = false;
         First_Buffer(buffer);
     }
     All_Buffers(buffer);
 }
Exemplo n.º 24
0
 /// <summary>
 /// Replace current PacketStream with some bytes from provided byte array.
 /// </summary>
 /// <param name="bytes"></param>
 /// <param name="offset"></param>
 /// <param name="count"></param>
 /// <returns></returns>
 public PacketStream Replace(Byte[] bytes, Int32 offset, Int32 count)
 {
     Reserve(count);
     SBuffer.BlockCopy(bytes, offset, Buffer, 0, count);
     Count = count;
     return(this);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Reads a sequence of bytes from the stream and advances the position
        /// within the stream by the number of bytes read.
        /// </summary>
        /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many
        /// bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The buffer offset.</param>
        /// <param name="count">The number of bytes to read.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="buffer"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <para><paramref name="offset"/> is less than zero or greater than the length of <paramref name="buffer"/>.</para>
        /// <para>-or-</para>
        /// <para>The <paramref name="buffer"/> is not large enough to contain <paramref name="count"/> bytes strting
        /// at the specified <paramref name="offset"/>.</para>
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">
        /// The stream has been disposed.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// The stream is in token mode (see <see cref="ImapStreamMode.Token"/>).
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public int Read(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            CheckDisposed();

            ValidateArguments(buffer, offset, count);

            if (Mode != ImapStreamMode.Literal)
            {
                return(0);
            }

            count = Math.Min(count, literalDataLeft);

            int length = inputEnd - inputIndex;
            int n;

            if (length < count && length <= ReadAheadSize)
            {
                ReadAhead(BlockSize, cancellationToken);
            }

            length = inputEnd - inputIndex;
            n      = Math.Min(count, length);

            Buffer.BlockCopy(input, inputIndex, buffer, offset, n);
            literalDataLeft -= n;
            inputIndex      += n;

            if (literalDataLeft == 0)
            {
                Mode = ImapStreamMode.Token;
            }

            return(n);
        }
Exemplo n.º 26
0
        public Skybox(GraphicsDevice device)
        {
            float x = 0.525731f;
            float z = 0.850651f;

            var vertices = new SkyboxVertex[12]
            {
                new SkyboxVertex(-x, 0f, z), new SkyboxVertex(x, 0f, z),
                new SkyboxVertex(-x, 0f, -z), new SkyboxVertex(x, 0f, -z),
                new SkyboxVertex(0f, z, x), new SkyboxVertex(0f, z, -x),
                new SkyboxVertex(0f, -z, x), new SkyboxVertex(0f, -z, -x),
                new SkyboxVertex(z, x, 0f), new SkyboxVertex(-z, x, 0f),
                new SkyboxVertex(z, -x, 0f), new SkyboxVertex(-z, -x, 0f),
            };

            var indices = new int[60]
            {
                1,4,0,  4,9,0,  4,5,9,  8,5,4,  1,8,4,
                1,10,8, 10,3,8, 8,3,5,  3,2,5,  3,7,2,
                3,10,7, 10,6,7, 6,11,7, 6,0,11, 6,1,0,
                10,1,6, 11,0,9, 2,11,9, 5,2,9,  11,2,7
            };

            vertexBuffer = Buffer<SkyboxVertex>.New(device, vertices, BufferFlags.VertexBuffer);
            indexBuffer = Buffer<int>.New(device, indices, BufferFlags.IndexBuffer);
            skyboxEffect = EffectLoader.Load(@"Graphics/Shaders/Skybox.fx");
            skyboxTex = Texture2D.Load(device, @"G:\Users\Athrun\Documents\Stratum\trunk\src\Stratum\WorldEngine\Earth\milkyWay.tif");
        }
Exemplo n.º 27
0
        public ConsoleViewModel(
            ISyncThingManager syncThingManager,
            IConfigurationProvider configurationProvider)
        {
            this.syncThingManager = syncThingManager;
            this.LogMessages = new Queue<string>();

            // Display log messages 100ms after the previous message, or every 500ms if they're arriving thick and fast
            this.logMessagesBuffer = new Buffer<string>(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(500));
            this.logMessagesBuffer.Delivered += (o, e) =>
            {
                foreach (var message in e.Items)
                {
                    this.LogMessages.Enqueue(message);
                    if (this.LogMessages.Count > maxLogMessages)
                        this.LogMessages.Dequeue();
                }

                this.NotifyOfPropertyChange(() => this.LogMessages);
            };

            this.syncThingManager.MessageLogged += (o, e) =>
            {
                this.logMessagesBuffer.Add(e.LogMessage);
            };
        }
Exemplo n.º 28
0
        public Worker(int threadCount, int blockLength, IHash hasher, FileStream stream)
        {
            mainThread = Thread.CurrentThread;
            this.threadCount = threadCount;
            this.stream = stream;
            this.hasher = hasher;

            this.blockLength = blockLength;
            threads = new List<Thread>(threadCount);

            for (int i = 0; i < threadCount; ++i)
            {
                var b = new Buffer();
                b.raw = new byte[blockLength];
                bufferQueue.AddToQueue(b);
            }

            blockCount = stream.Length / blockLength;
            if (stream.Length % blockLength != 0)
            {
                blockCount++;
            }

            Console.CancelKeyPress += new ConsoleCancelEventHandler(Cancel);
        }
Exemplo n.º 29
0
        public void WriteString(Encoding encoding, string value)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (value == null)
            {
                Write7BitEncodedInt(-1);
                return;
            }

            byte[] data = encoding.GetBytes(value);
            int    additionalCapacity = sizeof(int) + data.Length;

            if (this.position + additionalCapacity >= this.buffer.Length)
            {
                int curLength = this.buffer.Length;
                int newLength = curLength * 2;
                while (newLength <= curLength + additionalCapacity)
                {
                    newLength *= 2;
                }

                byte[] newbuffer = new byte[newLength];
                Buff.BlockCopy(this.buffer, 0, newbuffer, 0, this.Length);
                this.buffer = newbuffer;
            }

            Write7BitEncodedInt(data.Length);
            Buff.BlockCopy(data, 0, this.buffer, this.position, data.Length);
            this.position += data.Length;
        }
Exemplo n.º 30
0
        //
        // This validation logic is a manual port of StrongNameIsValidPublicKey() in the desktop CLR (see clr\src\StrongName\api\StrongNameInternal.cpp)
        //
        private static bool IsValidPublicKey(byte[] publicKey)
        {
            uint publicKeyLength = (uint)(publicKey.Length);

            // The buffer must be at least as large as the public key structure (for compat with desktop, we actually compare with the size of the header + 4).
            if (publicKeyLength < SizeOfPublicKeyBlob + 4)
            {
                return(false);
            }


            // Poor man's reinterpret_cast into the PublicKeyBlob structure.
            uint[] publicKeyBlob = new uint[3];
            Buffer.BlockCopy(publicKey, 0, publicKeyBlob, 0, (int)SizeOfPublicKeyBlob);
            uint sigAlgID    = publicKeyBlob[0];
            uint hashAlgID   = publicKeyBlob[1];
            uint cbPublicKey = publicKeyBlob[2];

            // The buffer must be the same size as the structure header plus the trailing key data
            if (cbPublicKey != publicKeyLength - SizeOfPublicKeyBlob)
            {
                return(false);
            }

            // The buffer itself looks reasonable, but the public key structure needs to be validated as well

            // The ECMA key doesn't look like a valid key so it will fail the below checks. If we were passed that
            // key, then we can skip them.
            if (ByteArrayEquals(publicKey, s_ecmaKey))
            {
                return(true);
            }

            // If a hash algorithm is specified, it must be a sensible value
            bool fHashAlgorithmValid = GetAlgClass(hashAlgID) == ALG_CLASS_HASH && GetAlgSid(hashAlgID) == ALG_SID_SHA1;

            if (hashAlgID != 0 && !fHashAlgorithmValid)
            {
                return(false);
            }

            // If a signature algorithm is specified, it must be a sensible value
            bool fSignatureAlgorithmValid = GetAlgClass(sigAlgID) == ALG_CLASS_SIGNATURE;

            if (sigAlgID != 0 && !fSignatureAlgorithmValid)
            {
                return(false);
            }

            // The key blob must indicate that it is a PUBLICKEYBLOB
            if (publicKey[SizeOfPublicKeyBlob] != PUBLICKEYBLOB)
            {
                return(false);
            }

            //@todo: Desktop also tries to import the public key blob using the Crypto api as further validation - not clear if there's any non-banned API to do this.

            return(true);
        }
Exemplo n.º 31
0
        // Draw_CachePic
        public static glpic_t CachePic(string path)
        {
            for (int i = 0; i < _MenuNumCachePics; i++)
            {
                cachepic_t p = _MenuCachePics[i];
                if (p.name == path) // !strcmp(path, pic->name))
                {
                    return(p.pic);
                }
            }

            if (_MenuNumCachePics == MAX_CACHED_PICS)
            {
                sys.Error("menu_numcachepics == MAX_CACHED_PICS");
            }

            cachepic_t pic = _MenuCachePics[_MenuNumCachePics];

            _MenuNumCachePics++;
            pic.name = path;

            //
            // load the pic from disk
            //
            byte[] data = common.LoadFile(path);
            if (data == null)
            {
                sys.Error("Draw_CachePic: failed to load {0}", path);
            }
            dqpicheader_t header = sys.BytesToStructure <dqpicheader_t>(data, 0);

            wad.SwapPic(header);

            int headerSize = Marshal.SizeOf(typeof(dqpicheader_t));

            // HACK HACK HACK --- we need to keep the bytes for
            // the translatable player picture just for the menu
            // configuration dialog
            if (path == "gfx/menuplyr.lmp")
            {
                Buffer.BlockCopy(data, headerSize, _MenuPlayerPixels, 0, header.width * header.height);
                //memcpy (menuplyr_pixels, dat->data, dat->width*dat->height);
            }

            glpic_t gl = new glpic_t();

            gl.width  = header.width;
            gl.height = header.height;

            //gl = (glpic_t *)pic->pic.data;
            gl.texnum = LoadTexture(gl, new ByteArraySegment(data, headerSize));
            gl.sl     = 0;
            gl.sh     = 1;
            gl.tl     = 0;
            gl.th     = 1;
            pic.pic   = gl;

            return(gl);
        }
 /**
  * Factory method to create an unmodifiable buffer.
  * <p>
  * If the buffer passed in is already unmodifiable, it is returned.
  *
  * @param buffer  the buffer to decorate, must not be null
  * @return an unmodifiable Buffer
  * @throws IllegalArgumentException if buffer is null
  */
 public static Buffer decorate(Buffer buffer)
 {
     if (buffer is Unmodifiable)
     {
         return buffer;
     }
     return new UnmodifiableBuffer(buffer);
 }
Exemplo n.º 33
0
        public static byte[] ArrayConcat(byte[] a, byte[] b)
        {
            byte[] c = new byte[a.Length + b.Length];
            Buffer.BlockCopy(a, 0, c, 0, a.Length);
            Buffer.BlockCopy(b, 0, c, a.Length, b.Length);

            return(c);
        }
Exemplo n.º 34
0
        public virtual void Initialize()
        {
            GraphicsDevice device = Engine.GraphicsContext.Device;

            wireFrame = EffectLoader.Load(@"World/Earth/Shaders/DeferredTerrain.fx");

            vertexBuffer = Buffer<TerrainVertex>.New<TerrainVertex>(device, SharpDX.Utilities.SizeOf<TerrainVertex>() * 4 * 1000, BufferFlags.VertexBuffer, SharpDX.Direct3D11.ResourceUsage.Dynamic);
        }
Exemplo n.º 35
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf <T>();
            var bytes    = formatter.ReadBytes(itemSize * rows);

            Data = new T[rows];
            Buffer.BlockCopy(bytes, 0, Data, 0, itemSize * rows);
        }
 /// <summary>
 ///   Sets a single constant buffer to be used by the shader stage.
 /// </summary>
 /// <param name = "slot">Index into the device's zero-based array to which to set the constant buffer.</param>
 /// <param name = "constantBuffer">constant buffer to set</param>
 public void SetConstantBuffer(int slot, Buffer constantBuffer)
 {
     var tempPtr = constantBuffer == null ? IntPtr.Zero : constantBuffer.NativePointer;
     unsafe
     {
         SetConstantBuffers(slot, 1, new IntPtr(&tempPtr));
     }
 }
Exemplo n.º 37
0
 public int InverseTransform(Buffer buffer, int length)
 {
     for (int i = 0; i < length; ++i)
     {
         buffer[i] = (byte)~buffer[i];
     }
     return length;
 }
Exemplo n.º 38
0
 public int Transform(Buffer buffer, int length)
 {
     for (int i = buffer.Length - length; i < buffer.Length; ++i)
     {
         buffer[i] = (byte)~buffer[i];
     }
     return length;
 }
Exemplo n.º 39
0
 public MyModel(LabGame game, VertexPositionColor[] shapeArray, String textureName, float collisionRadius)
 {
     this.vertices = Buffer.Vertex.New(game.GraphicsDevice, shapeArray);
     this.inputLayout = VertexInputLayout.New<VertexPositionColor>(0);
     vertexStride = Utilities.SizeOf<VertexPositionColor>();
     modelType = ModelType.Colored;
     this.collisionRadius = collisionRadius;
 }
Exemplo n.º 40
0
 public static void Copy(Buffer dst, Buffer src)
 {
     dst.buf = src.buf;
     dst.bufsize = src.bufsize;
     dst.bytepos = src.bytepos;
     dst.bitpos = src.bitpos;
     dst.error = src.error;
 }
Exemplo n.º 41
0
 public ParserGen(Parser parser)
 {
     tab = parser.tab;
     trace = parser.trace;
     buffer = parser.scanner.buffer;
     errorNr = -1;
     usingPos = null;
 }
Exemplo n.º 42
0
        public RadioTower(Vector3 pos)
        {
            bounds = new Circle(pos, 2);
            commCircle = new Circle(pos, 25);

            inbox = new Buffer<Message>(20);
            outbox = new Buffer<Message>(20);
        }
Exemplo n.º 43
0
 public void AddBuffer(Buffer buffer)
 {
     buffer.X = this.Left;
     buffer.Y = this.Top;
     buffer.Width = this.Width;
     buffer.Height = this.Height;
     this.Buffers.AddLast(buffer);
     this.CurrentBufferNode = this.Buffers.Last;
 }
Exemplo n.º 44
0
        public override void Write(ProtocolFormatter formatter, int rows)
        {
            Debug.Assert(Rows == rows, "Row count mismatch!");
            var itemSize = Marshal.SizeOf <T>();
            var bytes    = new byte[itemSize * rows];

            Buffer.BlockCopy(Data, 0, bytes, 0, itemSize * rows);
            formatter.WriteBytes(bytes);
        }
Exemplo n.º 45
0
        public static long GetRSAFingerprint(string key)
        {
            using (var text = new StringReader(key))
            {
                var reader    = new PemReader(text);
                var parameter = reader.ReadObject() as RsaKeyParameters;
                if (parameter != null)
                {
                    var modulus  = parameter.Modulus.ToByteArray();
                    var exponent = parameter.Exponent.ToByteArray();

                    if (modulus.Length > 256)
                    {
                        var corrected = new byte[256];
                        Buffer.BlockCopy(modulus, modulus.Length - 256, corrected, 0, 256);

                        modulus = corrected;
                    }
                    else if (modulus.Length < 256)
                    {
                        var corrected = new byte[256];
                        Buffer.BlockCopy(modulus, 0, corrected, 256 - modulus.Length, modulus.Length);

                        for (int a = 0; a < 256 - modulus.Length; a++)
                        {
                            modulus[a] = 0;
                        }

                        modulus = corrected;
                    }

                    using (var stream = new MemoryStream())
                    {
                        var modulusString  = TLString.FromBigEndianData(modulus);
                        var exponentString = TLString.FromBigEndianData(exponent);

                        modulusString.ToStream(stream);
                        exponentString.ToStream(stream);

                        var hash = ComputeSHA1(stream.ToArray());

                        var fingerprint = (((ulong)hash[19]) << 56) |
                                          (((ulong)hash[18]) << 48) |
                                          (((ulong)hash[17]) << 40) |
                                          (((ulong)hash[16]) << 32) |
                                          (((ulong)hash[15]) << 24) |
                                          (((ulong)hash[14]) << 16) |
                                          (((ulong)hash[13]) << 8) |
                                          ((ulong)hash[12]);

                        return((long)fingerprint);
                    }
                }
            }

            return(-1);
        }
        private static void GetByteVertexAndIndexBuffer(out byte[] byteVertexBuffer, out int[] indexBuffer)
        {
            float[] floatVertexBuffer;
            GetFloatVertexAndIndexBuffer(out floatVertexBuffer, out indexBuffer);

            // Copy float array into byte array
            byteVertexBuffer = new byte[floatVertexBuffer.Length * 4];
            Buffer.BlockCopy(floatVertexBuffer, 0, byteVertexBuffer, 0, byteVertexBuffer.Length);
        }
Exemplo n.º 47
0
 public BitStream()
 {
     m_first = new Buffer();
     m_last = m_first;
     m_blockingRead = false;
     m_streamEnded = false;
     m_lock = new object();
     Rewind();
 }
Exemplo n.º 48
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = sizeof(ushort);
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new ushort[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddDays(x)).ToArray();
        }
Exemplo n.º 49
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf(typeof(Guid));
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new Guid[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.ToArray();
        }
Exemplo n.º 50
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
            var itemSize = Marshal.SizeOf <uint>();
            var bytes    = formatter.ReadBytes(itemSize * rows);
            var xdata    = new uint[rows];

            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddSeconds(x)).ToArray();
        }
Exemplo n.º 51
0
 public PacketStream Insert(Int32 offset, Byte[] copyArray, Int32 copyArrayOffset, Int32 count)
 {
     Reserve(Count + count);
     // передвигаем данные с позиции offset до позиции offset + count
     SBuffer.BlockCopy(Buffer, offset, Buffer, offset + count, Count - offset);
     // копируем новый массив данных в позицию offset
     SBuffer.BlockCopy(copyArray, copyArrayOffset, Buffer, offset, count);
     Count += count;
     return(this);
 }
Exemplo n.º 52
0
        public byte[] ReadBytes()
        {
            int len = ReadInt32();

            byte[] b = new byte[len];
            Buff.BlockCopy(this.buffer, this.Position, b, 0, len);
            this.Position += len;

            return(b);
        }
 //-----------------------------------------------------------------------
 /**
  * Constructor that wraps (not copies) another buffer, making it bounded
  * waiting only up to a maximum amount of time.
  *
  * @param buffer  the buffer to wrap, must not be null
  * @param maximumSize  the maximum size, must be size one or greater
  * @param timeout  the maximum amount of time to wait
  * @throws IllegalArgumentException if the buffer is null
  * @throws IllegalArgumentException if the maximum size is zero or less
  */
 protected BoundedBuffer(Buffer buffer, int maximumSize, long timeout)
     : base(buffer)
 {
     if (maximumSize < 1)
     {
         throw new java.lang.IllegalArgumentException();
     }
     this.maximumSize = maximumSize;
     this.timeout = timeout;
 }
Exemplo n.º 54
0
        public void Write(void *data, nuint length)
        {
            if (length > Size)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(nameof(data), "Cannot write segment larger than ring buffer segment size.");
            }

            _RingSync.WaitEnterNext();
            Buffer.MemoryCopy(data, _Pointer + GetCurrentOffset(), Size, length);
        }
Exemplo n.º 55
0
        public Map(GraphicsDevice device, int width, int height)
        {
            this.width = width;
            this.height = height;

            objectMap = new Buffer<GameObject>[width, height];
            initGrid();

            neighborList = new Buffer<GameObject>(40);
        }
Exemplo n.º 56
0
        async Task <int> ReadAheadAsync(bool doAsync, CancellationToken cancellationToken)
        {
            int left = inputEnd - inputIndex;
            int index, nread;

            if (left > 0)
            {
                if (inputIndex > 0)
                {
                    // move all of the remaining input to the beginning of the buffer
                    Buffer.BlockCopy(input, inputIndex, input, 0, left);
                    inputEnd   = left;
                    inputIndex = 0;
                }
            }
            else
            {
                inputIndex = 0;
                inputEnd   = 0;
            }

            left  = input.Length - inputEnd;
            index = inputEnd;

            try {
                var network = Stream as NetworkStream;

                cancellationToken.ThrowIfCancellationRequested();

                if (doAsync)
                {
                    nread = await Stream.ReadAsync(input, index, left, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    network?.Poll(SelectMode.SelectRead, cancellationToken);
                    nread = Stream.Read(input, index, left);
                }

                if (nread > 0)
                {
                    logger.LogServer(input, index, nread);
                    inputEnd += nread;
                }
                else
                {
                    throw new SmtpProtocolException("The SMTP server has unexpectedly disconnected.");
                }
            } catch {
                IsConnected = false;
                throw;
            }

            return(inputEnd - inputIndex);
        }
Exemplo n.º 57
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = Marshal.SizeOf(typeof(T));
#else
            var itemSize = Marshal.SizeOf <T>();
#endif
            var bytes = formatter.ReadBytes(itemSize * rows);
            Data = new T[rows];
            Buffer.BlockCopy(bytes, 0, Data, 0, itemSize * rows);
        }
Exemplo n.º 58
0
        internal override void Read(ProtocolFormatter formatter, int rows)
        {
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = sizeof(ushort);
#else
            var itemSize = Marshal.SizeOf <ushort>();
#endif
            var bytes = formatter.ReadBytes(itemSize * rows);
            var xdata = new ushort[rows];
            Buffer.BlockCopy(bytes, 0, xdata, 0, itemSize * rows);
            Data = xdata.Select(x => UnixTimeBase.AddDays(x)).ToArray();
        }
Exemplo n.º 59
0
        public Byte[] ReadBytes(Int32 count)
        {
            if (Pos + count > Count)
            {
                throw new MarshalException();
            }

            Byte[] result = new Byte[count];
            SBuffer.BlockCopy(Buffer, Pos, result, 0, count);
            Pos += count;
            return(result);
        }
Exemplo n.º 60
0
        public override void Write(ProtocolFormatter formatter, int rows)
        {
            Debug.Assert(Rows == rows, "Row count mismatch!");
#if FRAMEWORK20 || FRAMEWORK40 || FRAMEWORK45
            var itemSize = Marshal.SizeOf(typeof(T));
#else
            var itemSize = Marshal.SizeOf <T>();
#endif
            var bytes = new byte[itemSize * rows];
            Buffer.BlockCopy(Data, 0, bytes, 0, itemSize * rows);
            formatter.WriteBytes(bytes);
        }