Esempio n. 1
0
 //private DataNodeCollection _executingData;
 public DataStreams()
 {
     // The sequence will have at least one stream to hold effect data.
     _mainStream = new DataStream("Main");
     _dataStreams.Add(_mainStream);
     //_executingData = new DataNodeCollection();
 }
Esempio n. 2
0
 public BitmapImage(int width, int height, BitmapProperties properties)
 {
     mWidth = width;
     mHeight = height;
     mProperties = properties;
     mData = new DataStream(width * height * 4, true, true);
 }
Esempio n. 3
0
        public MyGrassPatch(HeightMap heightMap, int size)
        {
            MyGrassPatch.width = size;
            MyGrassPatch.length = size;
            this.heightMap = heightMap;
            System.Random rSeed = new Random();

            //triangleCount = length * width * bladeBySquare * bladeBySquare * nbSegment * 2 * 4 * 2;
            triangleCount = length * width * bladeBySquare * bladeBySquare * nbSegment * 4;

            vertices = new DataStream((12+8) * triangleCount * 3, true, true);
            for (int i = 0; i < width;i++)
                for (int j = 0; j < length; j++)
                {
                    for (int xb = 0;xb < bladeBySquare;xb++)
                        for (int yb = 0; yb < bladeBySquare; yb++)
                        {
                            float x = i + xb * 1f / bladeBySquare + ((float)rSeed.NextDouble()-0.5f) * 0.2f;
                            float z = j + yb * 1f / bladeBySquare + ((float)rSeed.NextDouble() - 0.5f) * 0.2f;
                            //float x = i + xb * 1f / bladeBySquare;
                            //float z = j + yb * 1f / bladeBySquare;
                            addBlade(x, heightMap.getHeight(x, z), z, 1.0f + (float)rSeed.NextDouble() * 0.2f, (float)(rSeed.NextDouble()*Math.PI));
                        }
                }
            vertices.Position = 0;
        }
Esempio n. 4
0
        public MyTerrain(HeightMap heightMap,int size)
        {
            MyTerrain.width = size;
            MyTerrain.length = size;
            this.heightMap = heightMap;

            vertices = new DataStream((12+8) * triangleCount * 3, true, true);
            for (int i = 0; i < width;i++)
                for (int j = 0; j < length; j++)
                {
                    float height;
                    height = heightMap.getHeight((float)i, (float)j);
                    vertices.Write(new Vector3(0.0f + i, height, 0.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));
                    height = heightMap.getHeight((float)i, (float)j+1f);
                    vertices.Write(new Vector3(0.0f + i, height, 1.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));
                    height = heightMap.getHeight((float)i+1, (float)j);
                    vertices.Write(new Vector3(1.0f + i, height, 0.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));
                    height = heightMap.getHeight((float)i, (float)j + 1);
                    vertices.Write(new Vector3(0.0f + i, height, 1.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));
                    height = heightMap.getHeight((float)i + 1, (float)j + 1);
                    vertices.Write(new Vector3(1.0f + i, height, 1.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));
                    height = heightMap.getHeight((float)i + 1, (float)j);
                    vertices.Write(new Vector3(1.0f + i, height, 0.0f + j));
                    vertices.Write(new Vector2(0.0f, 0.0f));

                }
            vertices.Position = 0;
        }
Esempio n. 5
0
 /// <summary>
 /// Creates a <see cref="SharpDX.Direct3D11.Texture2D"/> from a WIC <see cref="SharpDX.WIC.BitmapSource"/>
 /// </summary>
 /// <param name="device">The Direct3D11 device</param>
 /// <param name="bitmapSource">The WIC bitmap source</param>
 /// <returns>A Texture2D</returns>
 public static Texture2D CreateTexture2DFromBitmap(Device device, BitmapSource bitmapSource)
 {
     // Allocate DataStream to receive the WIC image pixels
         int stride = bitmapSource.Size.Width * 4;
         using (var buffer = new DataStream(bitmapSource.Size.Height * stride, true, true))
         {
         // Copy the content of the WIC to the buffer
         Rectangle rect = new Rectangle();
         var methods = bitmapSource.GetType().GetMethods();
         bitmapSource.GetType().GetMethods().First(item => item.Name == "CopyPixels").Invoke(bitmapSource, new object[] { stride, buffer });
           //  bitmapSource.CopyPixels(stride, buffer);
             return new Texture2D(device, new Texture2DDescription()
             {
                 Width = bitmapSource.Size.Width,
                 Height = bitmapSource.Size.Height,
                 ArraySize = 1,
                 BindFlags = BindFlags.ShaderResource,
                 Usage = ResourceUsage.Immutable,
                 CpuAccessFlags =CpuAccessFlags.None,
                 Format = Format.R8G8B8A8_UNorm,
                 MipLevels = 1,
                 OptionFlags = ResourceOptionFlags.None,
                 SampleDescription = new SampleDescription(1, 0),
             }, new DataRectangle(buffer.DataPointer, stride));
         }
 }
Esempio n. 6
0
        public Sections(Reader reader)
        {
            this.memStream = reader.memStream;
            this.binaryParser = reader.binaryParser;
            this.sectionCount = (int)(reader.GetFileHeader().GetNumberOfSections());
            long optHeaderAddress = reader.GetDOSHeader().GetFileAddress() + fileHeaderLength;
            long dataDirectoryAddress = optHeaderAddress + optHeaderLength;
            sectionAddress = (dataDirectoryAddress + dataDirectorySize) + sectionPadding + 0x4;

            for (int i = 0; i < sectionCount; i++)
            {
                long count = sectionLength * i;
                long offset = sectionAddress + count;
                memStream.Position = offset;
                string name = Encoding.Default.GetString(binaryParser.ReadBytes(8));
                UInt32 virtualSize = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0xc;
                UInt32 virtualAddress = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0x10;
                UInt32 rawDataSize = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0x14;
                UInt32 rawDataAddress = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0x18;
                UInt32 relocAddress = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0x1c;
                UInt32 lineAddress = (UInt32)(memStream.Position = binaryParser.ReadUInt32());
                memStream.Position = offset + 0x20;
                UInt16 relocCount = (UInt16)(memStream.Position = binaryParser.ReadUInt16());
                memStream.Position = offset + 0x22;
                UInt16 lineCount = (UInt16)(memStream.Position = binaryParser.ReadUInt16());

                this.allSections.Add(new Section(name, virtualAddress, virtualSize, rawDataSize, rawDataAddress, relocAddress, lineAddress, relocCount, lineCount));
            }
        }
Esempio n. 7
0
        public static Image CopyTextureToBitmap(D3D.Texture2D texture)
        {
            int width = texture.Description.Width;
            if (width % 16 != 0)
                width = MathExtensions.Round(width, 16) + 16;
            Bitmap bmp = new Bitmap(texture.Description.Width, texture.Description.Height, PixelFormat.Format32bppArgb);
            BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
            using (DataStream stream = new DataStream(bData.Scan0, bData.Stride * bData.Height, false, true))
            {
                DataRectangle rect = texture.Map(0, D3D.MapMode.Read, D3D.MapFlags.None);
                using (DataStream texStream = rect.Data)
                {
                    for (int y = 0; y < texture.Description.Height; y++)
                        for (int x = 0; x < rect.Pitch; x+=4)
                        {
                            byte[] bytes = texStream.ReadRange<byte>(4);
                            if (x < bmp.Width*4)
                            {
                                stream.Write<byte>(bytes[2]);	// DXGI format is BGRA, GDI format is RGBA.
                                stream.Write<byte>(bytes[1]);
                                stream.Write<byte>(bytes[0]);
                                stream.Write<byte>(255);
                            }
                        }
                }
            }

            bmp.UnlockBits(bData);
            return bmp;
        }
Esempio n. 8
0
 public DataDirectories(Reader reader)
 {
     this.memStream = reader.memStream;
     this.binaryParser = reader.binaryParser;
     long optHeaderAddress = reader.GetDOSHeader().GetFileAddress() + fileHeaderLength;
     dataDirectoryAddress = optHeaderAddress + optHeaderLength;
 }
Esempio n. 9
0
        /// <summary>
        /// Initializes a new DirectXTexture class.
        /// </summary>
        /// <param name="bmp">The Bitmap.</param>
        internal DirectXTexture(System.Drawing.Bitmap bmp)
        {
            RawBitmap = (System.Drawing.Bitmap) bmp.Clone();
            _width = bmp.Width;
            _height = bmp.Height;
            var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height);
            var bitmapProperties = new BitmapProperties(
                new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96);
            var size = new Size2(bmp.Width, bmp.Height);

            int stride = bmp.Width*sizeof (int);
            using (var tempStream = new DataStream(bmp.Height*stride, true, true))
            {
                BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                for (int y = 0; y < bmp.Height; y++)
                {
                    int offset = bitmapData.Stride*y;
                    for (int x = 0; x < bmp.Width; x++)
                    {
                        byte b = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte g = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte r = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte a = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = r | (g << 8) | (b << 16) | (a << 24);
                        tempStream.Write(rgba);
                    }
                }
                bmp.UnlockBits(bitmapData);
                tempStream.Position = 0;
                _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties);
            }
        }
Esempio n. 10
0
        public static Texture2D TextureFromBitmap(Bitmap image)
        {
            BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                                             ImageLockMode.ReadWrite, image.PixelFormat);
            int bytes = data.Stride*image.Height;
            DataStream stream = new DataStream(bytes, true, true);
            stream.WriteRange(data.Scan0, bytes);
            stream.Position = 0;
            DataRectangle dRect = new DataRectangle(data.Stride, stream);

            Texture2DDescription texDesc = new Texture2DDescription
                                               {
                                                   ArraySize = 1,
                                                   MipLevels = 1,
                                                   SampleDescription = new SampleDescription(1, 0),
                                                   Format = Format.B8G8R8A8_UNorm,
                                                   CpuAccessFlags = CpuAccessFlags.None,
                                                   BindFlags = BindFlags.ShaderResource,
                                                   Usage = ResourceUsage.Immutable,
                                                   Height = image.Height,
                                                   Width = image.Width
                                               };

            image.UnlockBits(data);
            image.Dispose();
            Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect);
            stream.Dispose();
            return texture;
        }
Esempio n. 11
0
        public ShaderResourceView ToTexture3D(Device graphicsDevice, Format format)
        {
            int sizeInBytes = sizeof(float) * width * height * depth;

            DataStream stream = new DataStream(sizeInBytes, true, true);
            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    for (int z = 0; z < depth; z++)
                        stream.Write(values[x, y, z]);
            stream.Position = 0;

            DataBox dataBox = new DataBox(sizeof(float) * width, sizeof(float) * width * height, stream);
            Texture3DDescription description = new Texture3DDescription()
            {
                BindFlags = BindFlags.ShaderResource,
                CpuAccessFlags = CpuAccessFlags.None,
                Depth = depth,
                Format = format,
                Height = height,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                Usage = ResourceUsage.Default,
                Width = width
            };
            Texture3D texture = new Texture3D(graphicsDevice, description, dataBox);

            stream.Dispose();

            return new ShaderResourceView(graphicsDevice, texture);
        }
Esempio n. 12
0
        public void Create2(Vector3 topLeftVertex, int width, int height, DataStream stream)
        {
            TexturedVertex[] vertices = new TexturedVertex[]
                                            {
                                                new TexturedVertex(
                                                    new Vector4(topLeftVertex.X, topLeftVertex.Y-height, topLeftVertex.Z, 1.0f),
                                                    new Vector2(0.0f, 1.0f)),
                                                new TexturedVertex(
                                                    new Vector4(topLeftVertex.X, topLeftVertex.Y,
                                                                topLeftVertex.Z, 1.0f), new Vector2(0.0f, 0.0f)),
                                                new TexturedVertex(
                                                    new Vector4(topLeftVertex.X + width, topLeftVertex.Y,
                                                                topLeftVertex.Z, 1.0f), new Vector2(1.0f, 0.0f)),
                                                new TexturedVertex(
                                                    new Vector4(topLeftVertex.X + width, topLeftVertex.Y - height,
                                                                topLeftVertex.Z, 1.0f), new Vector2(1.0f, 1.0f))
                                            };

            //stream = new DataStream(4 * TexturedVertex.Stride, true, true);
            foreach (TexturedVertex vertex in vertices)
            {
                stream.Write(vertex.Position);
                stream.Write(vertex.TextureCoordinate);
            }

            stream.Position = 0;
        }
Esempio n. 13
0
        public ObjRenderer(Form1 F)
            : base(F.Device)
        {
            P = F;
            PortalRoomManager.Equals(null, null);
            S = new Sorter();
            string s0 = Environment.CurrentDirectory + "/resources/shaders/ambient_fast.fx";
            SB_V = ShaderBytecode.CompileFromFile(s0, "VS_STATIC", "vs_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            SB_P = ShaderBytecode.CompileFromFile(s0, "PS", "ps_4_0", ManagedSettings.ShaderCompileFlags, EffectFlags.None);
            VS = new VertexShader(F.Device.HadrwareDevice(), SB_V);
            PS = new PixelShader(F.Device.HadrwareDevice(), SB_P);
            IL = new InputLayout(Device.HadrwareDevice(), SB_V, StaticVertex.ies);
            BufferDescription desc = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 2 * 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc);
            dS = new DataStream(2 * 64, true, true);

            BufferDescription desc2 = new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = 64,
                BindFlags = BindFlags.ConstantBuffer
            };
            cBuf2 = new SlimDX.Direct3D11.Buffer(Device.HadrwareDevice(), desc2);
            dS2 = new DataStream(64, true, true);
        }
Esempio n. 14
0
		public static Model Load(string file, Device device)
		{
			XmlDocument document = new XmlDocument();
			document.Load(file);

			XmlNamespaceManager ns = new XmlNamespaceManager(document.NameTable);
			ns.AddNamespace("c", "http://www.collada.org/2005/11/COLLADASchema");

			// Read vertex positions
			var positionsNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry[@id='geom-Torus001']/c:mesh/c:source[@id='geom-Torus001-positions']/c:float_array[@id='geom-Torus001-positions-array']", ns);
			var indicesNode = document.SelectSingleNode("/c:COLLADA/c:library_geometries/c:geometry[@id='geom-Torus001']/c:mesh/c:triangles/c:p", ns);

			var positions = ParseVector3s(positionsNode.InnerText).ToArray();
			var indices = ParseInts(indicesNode.InnerText).ToArray();

			// Mixing concerns here, but oh well
			var positionsBuffer = new DataStream(positions, true, false);
			var indicesBuffer = new DataStream(indices, true, false);

			var model = new Model()
			{
				VertexBuffer = new Buffer(device, positionsBuffer, positions.Length * Vector3.SizeInBytes, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None),
				IndexBuffer = new Buffer(device, indicesBuffer, indices.Length * sizeof(int), ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None),
				IndexCount = indices.Length,
				VertexPositions = positions
			};

			return model;
		}
        public MeshContainer(Engine.Serialize.Mesh M)
        {
            if (M != null)
            {
                LocalAABBMax = M.AABBMax;
                LocalAABBMin = M.AABBMin;

                VertexsCount = M.VertexCount;
                FaceCount = M.FaceCount;
                BytesPerVertex = M.VertexData.Length / VertexsCount;

                using (var vertices = new DataStream(BytesPerVertex * VertexsCount, true, true))
                {
                    vertices.WriteRange<byte>(M.VertexData, 0, M.VertexData.Length);
                    vertices.Position = 0;
                    Vertexs = new Buffer(ModelViewer.Program.device, vertices, BytesPerVertex * VertexsCount, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                    binding = new VertexBufferBinding(Vertexs, BytesPerVertex, 0);
                }

                using (var indices = new DataStream(4 * FaceCount * 3, true, true))
                {
                    indices.WriteRange<byte>(M.IndexData, 0, M.IndexData.Length);
                    indices.Position = 0;
                    Indices = new Buffer(ModelViewer.Program.device, indices, 4 * FaceCount * 3, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
                }
            }
        }
Esempio n. 16
0
        private static DX11Effect LoadByteCode(byte[] bytecode)
        {
            DX11Effect shader = new DX11Effect();
            try
            {
                DataStream ds = new DataStream(bytecode.Length, true, true);
                ds.Write(bytecode, 0, bytecode.Length);
                shader.ByteCode = new ShaderBytecode(ds);

                //fs.Close();
                ds.Dispose();

                shader.IsCompiled = true;
                shader.ErrorMessage = "";

                shader.Preprocess();

            }
            catch (Exception ex)
            {
                shader.IsCompiled = false;
                shader.ErrorMessage = ex.Message;
                shader.DefaultEffect = null;
            }
            return shader;
        }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SoundEffect"/> class.
        /// </summary>
        /// <param name="audioManager">The associated audio manager instance.</param>
        /// <param name="name">The name of the current instance.</param>
        /// <param name="waveFormat">The format of the current instance.</param>
        /// <param name="buffer">The buffer containing audio data.</param>
        /// <param name="decodedPacketsInfo">The information regaring decoded packets.</param>
        internal SoundEffect(AudioManager audioManager, string name, WaveFormat waveFormat, DataStream buffer, uint[] decodedPacketsInfo)
        {
            AudioManager = audioManager;
            Name = name;
            Format = waveFormat;
            AudioBuffer = new AudioBuffer
            {
                Stream = buffer,
                AudioBytes = (int)buffer.Length,
                Flags = BufferFlags.EndOfStream,
            };
            LoopedAudioBuffer = new AudioBuffer
            {
                Stream = buffer,
                AudioBytes = (int)buffer.Length,
                Flags = BufferFlags.EndOfStream,
                LoopCount = AudioBuffer.LoopInfinite,
            };

            DecodedPacketsInfo = decodedPacketsInfo;

            Duration = Format.SampleRate > 0 ? TimeSpan.FromMilliseconds(GetSamplesDuration() * 1000 / Format.SampleRate) : TimeSpan.Zero;

            children = new List<WeakReference>();
            VoicePool = AudioManager.InstancePool.GetVoicePool(Format);
        }
Esempio n. 18
0
        private SharpDX.Direct2D1.Bitmap SDXBitmapFromSysBitmap(WindowRenderTarget device, System.Drawing.Bitmap bitmap)
        {
            var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
            var bitmapProperties = new BitmapProperties(new PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied));
            var size = new Size2(bitmap.Width, bitmap.Height);

            // Transform pixels from BGRA to RGBA
            int stride = bitmap.Width * sizeof(int);
            using (var tempStream = new DataStream(bitmap.Height * stride, true, true))
            {
                // Lock System.Drawing.Bitmap
                var bitmapData = bitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);

                // Convert all pixels 
                for (int y = 0; y < bitmap.Height; y++)
                {
                    int offset = bitmapData.Stride * y;
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        // Not optimized 
                        byte B = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte G = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte R = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        byte A = Marshal.ReadByte(bitmapData.Scan0, offset++);
                        int rgba = R | (G << 8) | (B << 16) | (A << 24);
                        tempStream.Write(rgba);
                    }

                }
                bitmap.UnlockBits(bitmapData);
                tempStream.Position = 0;

                return new SharpDX.Direct2D1.Bitmap(device, size, tempStream, stride, bitmapProperties);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceFontLoader"/> class.
        /// </summary>
        /// <param name="factory">The factory.</param>
        public ResourceFontLoader(Factory factory)
        {
            _factory = factory;
            foreach (var name in typeof(ResourceFontLoader).Assembly.GetManifestResourceNames())
            {
                if (name.EndsWith(".ttf"))
                {
                    var fontBytes = Utilities.ReadStream(typeof (ResourceFontLoader).Assembly.GetManifestResourceStream(name));
                    var stream = new DataStream(fontBytes.Length, true, true);
                    stream.Write(fontBytes, 0, fontBytes.Length);
                    stream.Position = 0;
                    _fontStreams.Add(new ResourceFontFileStream(stream));
                }
            }

            // Build a Key storage that stores the index of the font
            _keyStream = new DataStream(sizeof(int) * _fontStreams.Count, true, true);
            for (int i = 0; i < _fontStreams.Count; i++ )
                _keyStream.Write((int)i);
            _keyStream.Position = 0;

            // Register the 
            _factory.RegisterFontFileLoader(this);
            _factory.RegisterFontCollectionLoader(this);
        }
Esempio n. 20
0
 /// <summary>	
 /// Performs any effect-specific initialization.	
 /// </summary>	
 /// <param name="stream"> Effect-specific initialization parameters, may be NULL if DataByteSize is 0. </param>
 /// <returns>No documentation.</returns>
 /// <unmanaged>HRESULT IXAPO::Initialize([In, Buffer, Optional] const void* pData,[None] UINT32 DataByteSize)</unmanaged>
 public void Initialize(DataStream stream)
 {
     if (stream == null)
         Initialize_(IntPtr.Zero, 0);
     else
     Initialize_(stream.PositionPointer, (int)(stream.Length - stream.Position));
 }
        /// <summary>
        /// Gets an auth server list for a specific username.
        /// </summary>
        /// <param name="userName">The username.</param>
        /// <returns>A list of servers on success; otherwise, <c>null</c>.</returns>
        public IPEndPoint[] GetAuthServerList( string userName )
        {
            userName = userName.ToLower();

            byte[] userHash = CryptoHelper.JenkinsHash( Encoding.ASCII.GetBytes( userName ) );
            uint userData = BitConverter.ToUInt32( userHash, 0 ) & 1;

            TcpPacket packet = base.GetRawServerList( ESteam2ServerType.ProxyASClientAuthentication, NetHelpers.EndianSwap( userData ) );

            if ( packet == null )
                return null;

            DataStream ds = new DataStream( packet.GetPayload(), true );

            ushort numAddrs = ds.ReadUInt16();

            IPEndPoint[] serverList = new IPEndPoint[ numAddrs ];
            for ( int x = 0 ; x < numAddrs ; ++x )
            {
                IPAddrPort ipAddr = IPAddrPort.Deserialize( ds.ReadBytes( 6 ) );

                serverList[ x ] = ipAddr;
            }

            return serverList;
        }
Esempio n. 22
0
 public CLRHeader(Reader reader)
 {
     this.memStream = reader.memStream;
     this.binaryParser = reader.binaryParser;
     uint netDirectoryAddress = reader.GetDataDirectories().GetNETMetadataDirectory().GetAddress();
     this.clrHeaderAddress = (long)reader.RVAtoOffset(netDirectoryAddress);
 }
Esempio n. 23
0
		public static SlimDX.Direct3D11.Buffer InitQuadIndices(Device device)
		{
			ushort[] indices = new ushort[6 * MaxQuads];
			for(int i = 0; i < MaxQuads; ++i)
			{
				int baseVal = i * 4;
				int idx = i * 6;
				indices[idx + 0] = (ushort) (baseVal + 0);
				indices[idx + 1] = (ushort) (baseVal + 1);
				indices[idx + 2] = (ushort) (baseVal + 2);

				indices[idx + 3] = (ushort) (baseVal + 2);
				indices[idx + 4] = (ushort) (baseVal + 1);
				indices[idx + 5] = (ushort) (baseVal + 3);
			}

			using(var ds = new DataStream(indices, true, true))
			{
				ds.Position = 0;
				var buffer = new SlimDX.Direct3D11.Buffer(device, ds, new BufferDescription()
				{
					BindFlags = BindFlags.IndexBuffer,
					SizeInBytes = 12 * MaxQuads,
				});
				return buffer;
			}
		}
Esempio n. 24
0
        public DX11IndexBuffer(DX11RenderContext context, DataStream initial,bool dynamic, bool dispose)
        {
            this.context = context;
            format = SlimDX.DXGI.Format.R32_UInt;

            BindFlags flags = BindFlags.IndexBuffer;

            if (context.IsFeatureLevel11) { flags |= BindFlags.ShaderResource; }

            BufferDescription bd = new BufferDescription()
            {
                BindFlags = flags,
                CpuAccessFlags = dynamic ? CpuAccessFlags.Write : CpuAccessFlags.None,
                OptionFlags = context.IsFeatureLevel11 ? ResourceOptionFlags.RawBuffer : ResourceOptionFlags.None,
                SizeInBytes = (int)initial.Length,
                Usage = dynamic ? ResourceUsage.Dynamic : ResourceUsage.Default,
            };

            initial.Position = 0;
            this.IndicesCount = (int)initial.Length / 4;
            this.Buffer = new SlimDX.Direct3D11.Buffer(context.Device, initial, bd);

            this.CreateSRV();

            if (dispose) { initial.Dispose(); }
        }
Esempio n. 25
0
File: Reader.cs Progetto: 0xe9/Snile
 private Reader(DataStream memorySteam)
 {
     if (memStream == null)
         throw new Exception("Stream is null");
     this.memStream = memorySteam;
     this.binaryParser = new BinaryParser(memStream);
 }
Esempio n. 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SoundBank"/> class from a soundbank stream.
 /// </summary>
 /// <param name="audioEngine">The engine.</param>
 /// <param name="stream">The soundbank stream stream.</param>
 /// <unmanaged>HRESULT IXACT3Engine::CreateSoundBank([In] const void* pvBuffer,[In] unsigned int dwSize,[In] unsigned int dwFlags,[In] unsigned int dwAllocAttributes,[Out, Fast] IXACT3SoundBank** ppSoundBank)</unmanaged>
 public SoundBank(AudioEngine audioEngine, Stream stream)
 {
     this.audioEngine = audioEngine;
     isAudioEngineReadonly = true;
     soundBankSourceStream = stream as DataStream ?? DataStream.Create(Utilities.ReadStream(stream), true, true);
     audioEngine.CreateSoundBank(soundBankSourceStream.DataPointer, (int)soundBankSourceStream.Length, 0, 0, this);
 }
Esempio n. 27
0
        public IndexBuffer(Device device, ushort[] indices)
        {
            if(device == null)
            {
                throw new ArgumentNullException("device");
            }

            if(indices == null)
            {
                throw new ArgumentNullException("indices");
            }

            using(var dataStream = new DataStream(sizeof(UInt16)*indices.Length, true, true))
            {
                dataStream.WriteRange(indices);
                dataStream.Position = 0;

                Buffer = new Buffer(device,
                                    dataStream,
                                    (int) dataStream.Length,
                                    ResourceUsage.Immutable,
                                    BindFlags.IndexBuffer,
                                    CpuAccessFlags.None,
                                    ResourceOptionFlags.None,
                                    0);
            }

            Count = indices.Length;
        }
Esempio n. 28
0
        public Quad(int startX,int endX, int startZ, int endZ, Base.Content.Terrain.Terrain terrain, RenderManager renderer)
        {
            _bounds = new QuadBounds
            {
                MinX = startX / terrain.PointsPerMeter,
                MaxX = endX / terrain.PointsPerMeter,
                MinZ = startZ / terrain.PointsPerMeter,
                MaxZ = endZ / terrain.PointsPerMeter,
                MinY = terrain.Height[0],
                MaxY = terrain.Height[0]
            };
            HorizontalCenter = new Vector2(Bounds.MinX + (Bounds.MaxX - Bounds.MinX) / 2, Bounds.MinZ + (Bounds.MaxZ - Bounds.MinZ) / 2);

            int verticesX = endX - startX + 1;
            int verticesZ = endZ - startZ + 1;

            var dataStream = new DataStream(32 * verticesX * verticesZ, true, true);

            for (int i = 0; i < verticesX; i++)
            {
                for (int j = 0; j < verticesZ; j++)
                {
                    //Position
                    int xindex = Math.Min(i + startX, terrain.PointsX - 1);//Clamp to arraybounds if neccessary
                    int zindex = Math.Min(j + startZ, terrain.PointsZ - 1);//(Quadsize needs to be consistent for sharing IndexBuffers)
                    float x = xindex / terrain.PointsPerMeter;
                    float z = zindex / terrain.PointsPerMeter;
                    float y = terrain.Height[xindex * terrain.PointsZ + zindex];
                    dataStream.Write(new Vector3(x, y, z));

                    //Normal
                    float deltax = (terrain.Height[(xindex < terrain.PointsX - 1 ? xindex + 1 : xindex) * terrain.PointsZ + zindex]
                        - terrain.Height[(xindex != 0 ? xindex - 1 : xindex) * terrain.PointsZ + zindex]);

                    float deltaz = (terrain.Height[xindex * terrain.PointsZ + (zindex < terrain.PointsZ - 1 ? zindex + 1 : zindex)]
                        - terrain.Height[xindex * terrain.PointsZ + (zindex != 0 ? zindex - 1 : zindex)]);
                    if (xindex == 0 || xindex == terrain.PointsX - 1)
                        deltax *= 2;
                    if (zindex == 0 || zindex == terrain.PointsZ - 1)
                        deltaz *= 2;
                    var normal = new Vector3(-deltax, 2 / terrain.PointsPerMeter, deltaz);
                    normal.Normalize();
                    dataStream.Write(normal);

                    //TextureCoordinates
                    dataStream.Write(new Vector2(x / terrain.PointsX, z / terrain.PointsZ));

                    //Boundingbox-Params
                    if (y < _bounds.MinY)
                        _bounds.MinY = y;
                    if (y > _bounds.MaxY)
                        _bounds.MaxY = y;
                }
            }

            dataStream.Position = 0;
            VBuffer = new Buffer(renderer.D3DDevice, dataStream, 32 * verticesX * verticesZ, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            VertexBuffer = new VertexBufferBinding(VBuffer, 32, 0);
            dataStream.Dispose();
        }
Esempio n. 29
0
		private DataStream _GetRecordingStream()
		{
			if (_recordingStream == null) {
				_recordingStream = _sequence.SequenceData.DataStreams.CreateStream("Recording");
			}
			return _recordingStream;
		}
Esempio n. 30
0
        /// <summary>
        /// </summary>
        /// <param name="reader">
        /// </param>
        /// <param name="head">
        /// </param>
        /// <param name="bits">
        /// </param>
        internal MsfDirectory(PdbReader reader, PdbFileHeader head, BitAccess bits)
        {
            bits.MinCapacity(head.directorySize);
            var pages = reader.PagesFromSize(head.directorySize);

            // 0..n in page of directory pages.
            reader.Seek(head.directoryRoot, 0);
            bits.FillBuffer(reader.reader, pages * 4);

            var stream = new DataStream(head.directorySize, bits, pages);
            bits.MinCapacity(head.directorySize);
            stream.Read(reader, bits);

            // 0..3 in directory pages
            int count;
            bits.ReadInt32(out count);

            // 4..n
            var sizes = new int[count];
            bits.ReadInt32(sizes);

            // n..m
            this.streams = new DataStream[count];
            for (var i = 0; i < count; i++)
            {
                if (sizes[i] <= 0)
                {
                    this.streams[i] = new DataStream();
                }
                else
                {
                    this.streams[i] = new DataStream(sizes[i], bits, reader.PagesFromSize(sizes[i]));
                }
            }
        }
Esempio n. 31
0
 /// <summary>
 /// Supplies the analysis data to an analysis transform.
 /// </summary>
 /// <param name="analysisData"><para>The data that the transform will analyze.</para></param>
 /// <remarks>
 /// The output of the transform will be copied to CPU-accessible memory by the imaging effects system before being passed to the implementation.If this call fails, the corresponding <see cref="SharpDX.Direct2D1.Effect"/> instance is placed into an error state and fails to draw.
 /// </remarks>
 /// <unmanaged>HRESULT ID2D1AnalysisTransform::ProcessAnalysisResults([In, Buffer] const unsigned char* analysisData,[In] unsigned int analysisDataCount)</unmanaged>
 public void ProcessAnalysisResults(DataStream analysisData)
 {
     ProcessAnalysisResults(analysisData.DataPointer, (int)analysisData.Length);
 }
Esempio n. 32
0
        public void Resize()
        {
            Viewport vp     = this.DeviceManager.Context.Rasterizer.GetViewports()[0];
            int      width  = (int)vp.Width;
            int      height = (int)vp.Height;

            if (height == 0 || width == 0)
            {
                return;
            }
            this.TextureSize = new Vector2(width, height);
            float       w = width / 2f, h = height / 2f;
            List <byte> vertexBytes = new List <byte>();

            CGHelper.AddListBuffer(new Vector3(-w, h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(0, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector3(w, h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(1, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector3(-w, -h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(0, 1), vertexBytes);
            CGHelper.AddListBuffer(new Vector3(w, h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(1, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector3(w, -h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(1, 1), vertexBytes);
            CGHelper.AddListBuffer(new Vector3(-w, -h, 0), vertexBytes);
            CGHelper.AddListBuffer(new Vector2(0, 1), vertexBytes);
            using (DataStream ds = new DataStream(vertexBytes.ToArray(), true, true))
            {
                BufferDescription bufDesc = new BufferDescription()
                {
                    BindFlags   = BindFlags.VertexBuffer,
                    SizeInBytes = (int)ds.Length
                };
                if (this.VertexBuffer != null && !this.VertexBuffer.Disposed)
                {
                    this.VertexBuffer.Dispose();
                }
                this.VertexBuffer = new SlimDX.Direct3D11.Buffer(this.DeviceManager.Device, ds, bufDesc);
            }
            this.SpriteProjectionMatrix = Matrix.OrthoLH(width, height, 0, 100);
            this.spriteViewport         = new Viewport()
            {
                Width  = width,
                Height = height,
                MaxZ   = 1
            };


            this.ViewMatrix = Matrix.LookAtLH(new Vector3(0, 0, -1), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

            //DirectX11 for texture creation
            if (this.TextureD3D11 != null && !this.TextureD3D11.Disposed)
            {
                this.TextureD3D11.Dispose();
            }
            this.TextureD3D11 = new Texture2D(this.DeviceManager.Device, new Texture2DDescription()
            {
                Width             = width,
                Height            = height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = Format.B8G8R8A8_UNorm,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.RenderTarget | BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                OptionFlags       = ResourceOptionFlags.KeyedMutex
            });
            //Share DX10 and DX11 texture resources
            Resource sharedResource = new Resource(this.TextureD3D11);

            if (this.TextureD3D10 != null && !this.TextureD3D10.Disposed)
            {
                this.TextureD3D10.Dispose();
            }
            this.TextureD3D10 = this.DeviceManager.Device10.OpenSharedResource <SlimDX.Direct3D10.Texture2D>(sharedResource.SharedHandle);
            if (this.MutexD3D10 != null && !this.MutexD3D10.Disposed)
            {
                this.MutexD3D10.Dispose();
            }
            if (this.MutexD3D11 != null && !this.MutexD3D11.Disposed)
            {
                this.MutexD3D11.Dispose();
            }
            this.MutexD3D10 = new KeyedMutex(this.TextureD3D10);
            this.MutexD3D11 = new KeyedMutex(this.TextureD3D11);
            sharedResource.Dispose();
            Surface surface            = this.TextureD3D10.AsSurface();
            RenderTargetProperties rtp = new RenderTargetProperties();

            rtp.MinimumFeatureLevel = FeatureLevel.Direct3D10;
            rtp.Type        = RenderTargetType.Hardware;
            rtp.Usage       = RenderTargetUsage.None;
            rtp.PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied);
            if (this.DWRenderTarget != null && !this.DWRenderTarget.Disposed)
            {
                this.DWRenderTarget.Dispose();
            }
            this.DWRenderTarget = RenderTarget.FromDXGI(this.context.D2DFactory, surface, rtp);
            surface.Dispose();

            if (RenderTargetRecreated != null)
            {
                RenderTargetRecreated(this, new EventArgs());
            }
        }
Esempio n. 33
0
        public NodeContainerFormat Convert(BinaryFormat source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            source.Stream.Position = 0;

            var result = new NodeContainerFormat();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var reader = new DataReader(source.Stream)
            {
                DefaultEncoding = Encoding.GetEncoding(1252),
                Endianness      = EndiannessMode.BigEndian,
            };

            string magicId = reader.ReadString(4);

            if (magicId == "SLLZ")
            {
                var subStream  = new DataStream(source.Stream, 0, source.Stream.Length);
                var compressed = new ParFile(subStream);
                source = (ParFile)ConvertFormat.With <Sllz.Decompressor>(compressed);
                source.Stream.Position = 0;

                reader = new DataReader(source.Stream)
                {
                    DefaultEncoding = Encoding.GetEncoding(1252),
                    Endianness      = EndiannessMode.BigEndian,
                };

                magicId = reader.ReadString(4);
            }

            if (magicId != "PARC")
            {
                throw new FormatException("PARC: Bad magic Id.");
            }

            result.Root.Tags["Unknown#1"] = reader.ReadInt32();
            result.Root.Tags["Unknown#2"] = reader.ReadInt32();
            result.Root.Tags["Unknown#3"] = reader.ReadInt32();

            int totalFolderCount = reader.ReadInt32();
            int folderInfoOffset = reader.ReadInt32();
            int totalFileCount   = reader.ReadInt32();
            int fileInfoOffset   = reader.ReadInt32();

            var folderNames = new string[totalFolderCount];

            for (int i = 0; i < totalFolderCount; i++)
            {
                folderNames[i] = reader.ReadString(0x40).TrimEnd('\0');
            }

            var fileNames = new string[totalFileCount];

            for (int i = 0; i < totalFileCount; i++)
            {
                fileNames[i] = reader.ReadString(0x40).TrimEnd('\0');
            }

            reader.Stream.Seek(folderInfoOffset);
            var folders = new Node[totalFolderCount];

            for (int i = 0; i < totalFolderCount; i++)
            {
                folders[i] = new Node(folderNames[i], new NodeContainerFormat())
                {
                    Tags =
                    {
                        ["FolderCount"]      = reader.ReadInt32(),
                        ["FirstFolderIndex"] = reader.ReadInt32(),
                        ["FileCount"]        = reader.ReadInt32(),
                        ["FirstFileIndex"]   = reader.ReadInt32(),
                        ["Attributes"]       = reader.ReadInt32(),
                        ["Unknown2"]         = reader.ReadInt32(),
                        ["Unknown3"]         = reader.ReadInt32(),
                        ["Unknown4"]         = reader.ReadInt32(),
                    },
                };
            }

            reader.Stream.Seek(fileInfoOffset);
            var files = new Node[totalFileCount];

            for (int i = 0; i < totalFileCount; i++)
            {
                uint compressionFlag = reader.ReadUInt32();
                uint size            = reader.ReadUInt32();
                uint compressedSize  = reader.ReadUInt32();
                uint offset          = reader.ReadUInt32();
                int  attributes      = reader.ReadInt32();
                int  unknown2        = reader.ReadInt32();
                int  unknown3        = reader.ReadInt32();
                int  date            = reader.ReadInt32();

                var file = new ParFile(source.Stream, offset, compressedSize)
                {
                    CanBeCompressed  = false, // Don't try to compress if the original was not compressed.
                    IsCompressed     = compressionFlag == 0x80000000,
                    DecompressedSize = size,
                    Attributes       = attributes,
                    Unknown2         = unknown2,
                    Unknown3         = unknown3,
                    Date             = date,
                };

                files[i] = new Node(fileNames[i], file)
                {
                    Tags = { ["Date"] = date, },
                };
            }

            BuildTree(folders[0], folders, files, this.parameters);

            result.Root.Add(folders[0]);

            return(result);
        }
Esempio n. 34
0
 public override DataStream Serialize(DataStream ds)
 {
     ds.Write(WorldId);
     return(base.Serialize(ds));
 }
Esempio n. 35
0
 public SingleClass(DataStream data)
 {
     this.Var1 = data.GetString();
     this.Var2 = data.GetFloat();
 }
Esempio n. 36
0
    public override void Deserialize(DataStream reader)
    {
        base.Deserialize(reader);
        type = reader.ReadSInt32();
        NetTools.Log("RoomResp : " + type);

        switch (type)
        {
        case NetProtocols.ROOM_IN:
            rd = new RoomData();
            rd.Deserialize(reader);
            DeserializePlayerList(reader);
            break;

        case NetProtocols.ROOM_LEAVE:

            break;

        case NetProtocols.ROOM_INPLAYER:
//			uid = reader.ReadSInt64();
//			uname = reader.ReadString16();

            pm = new InRoomPlayerManager();
            pm.Deserialize(reader);
            break;

        case NetProtocols.ROOM_OUTPLAYER:
            uid = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_SEL_MODE:
            uid    = reader.ReadSInt64();
            modeid = reader.ReadSInt32();
            break;

        case NetProtocols.ROOM_READY:
            time    = reader.ReadSInt64();
            levelid = reader.ReadSInt32();
            break;

        case NetProtocols.ROOM_HIDE:
            time = reader.ReadSInt64();
            DeserializePlayerList(reader);
            break;

        case NetProtocols.ROOM_FIND:
            time = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_OVER:
            time = reader.ReadSInt64();

            wintype = reader.ReadByte();
            int rewardcount = reader.ReadSInt32();

            for (int i = 0; i < rewardcount; i++)
            {
                rewardList.Add(reader.ReadSInt32());
            }
            break;

        case NetProtocols.ROOM_RESULT:
            time = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_WAIT:
            time = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_PLAYER_DIE:
            sourceid = reader.ReadSInt64();
            targetid = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_SHOW_RAND_ITEM:
            item = InGameItem.Deserialize(reader);
            break;

        case NetProtocols.ROOM_GET_RAND_ITEM:
            item = InGameItem.Deserialize(reader);
            break;

        case NetProtocols.ROOM_USE_ITEM:
            item     = InGameItem.Deserialize(reader);
            targetid = reader.ReadSInt64();
            break;

        case NetProtocols.ROOM_PLAYER_LIFE:
            uid  = reader.ReadSInt64();
            life = reader.ReadSInt32();
            break;
        }
    }
Esempio n. 37
0
        public void GetPage()
        {
            // TODO: FIX ME!
            string pageLow = http_request_page.ToLowerFast();

#if PAGE_MAGIC
            if (pageLow.StartsWith("/map/region/"))
            {
                string after;
                string region = pageLow.Substring("/map/region/".Length).BeforeAndAfter("/", out after);
                for (int i = 0; i < TheServer.LoadedRegions.Count; i++)
                {
                    if (TheServer.LoadedRegions[i].Name == region)
                    {
                        string[] dat = after.SplitFast('/');
                        if (dat[0] == "img" && dat.Length >= 4)
                        {
                            int    x    = Utilities.StringToInt(dat[1]);
                            int    y    = Utilities.StringToInt(dat[2]);
                            int    z    = Utilities.StringToInt(dat[3].Before("."));
                            byte[] data = TheServer.LoadedRegions[i].ChunkManager.GetImage(x, y, z);
                            if (data != null)
                            {
                                http_response_contenttype = "image/png";
                                http_response_content     = data;
                                return;
                            }
                        }
                        else if (dat[0] == "full_img" && dat.Length >= 3)
                        {
                            int x = Utilities.StringToInt(dat[1]);
                            int y = Utilities.StringToInt(dat[2].Before("."));
                            KeyValuePair <int, int> maxes  = TheServer.LoadedRegions[i].ChunkManager.GetMaxes(x, y);
                            List <byte[]>           datums = new List <byte[]>();
                            for (int z = maxes.Key; z <= maxes.Value; z++)
                            {
                                byte[] dt = TheServer.LoadedRegions[i].ChunkManager.GetImage(x, y, z);
                                if (dt != null)
                                {
                                    datums.Add(dt);
                                }
                            }
                            http_response_contenttype = "image/png";
                            if (datums.Count > 1)
                            {
                                http_response_content = TheServer.BlockImages.Combine(datums, false);
                            }
                            else if (datums.Count == 1)
                            {
                                http_response_content = datums[0];
                            }
                            else
                            {
                                Bitmap bmp = new Bitmap(1, 1);
                                bmp.SetPixel(0, 0, Color.Black);
                                DataStream ds = new DataStream();
                                bmp.Save(ds, ImageFormat.Png);
                                http_response_content = ds.ToArray();
                                ds.Dispose();
                                bmp.Dispose();
                            }
                            return;
                        }
                        else if (dat[0] == "full_img_angle" && dat.Length >= 4)
                        {
                            int    x  = Utilities.StringToInt(dat[1]);
                            int    y  = Utilities.StringToInt(dat[2]);
                            int    z  = Utilities.StringToInt(dat[3].Before("."));
                            byte[] dt = TheServer.LoadedRegions[i].ChunkManager.GetImageAngle(x, y, z);
                            http_response_contenttype = "image/png";
                            if (dt != null)
                            {
                                http_response_content = dt;
                            }
                            else
                            {
                                Bitmap bmp = new Bitmap(1, 1);
                                bmp.SetPixel(0, 0, Color.Transparent);
                                DataStream ds = new DataStream();
                                bmp.Save(ds, ImageFormat.Png);
                                http_response_content = ds.ToArray();
                                ds.Dispose();
                                bmp.Dispose();
                            }
                            return;
                        }
                        else if (dat[0] == "maxes" && dat.Length >= 3)
                        {
                            int x = Utilities.StringToInt(dat[1]);
                            int y = Utilities.StringToInt(dat[2]);
                            KeyValuePair <int, int> maxes = TheServer.LoadedRegions[i].ChunkManager.GetMaxes(x, y);
                            http_response_content = FileHandler.encoding.GetBytes(maxes.Key + "," + maxes.Value);
                            return;
                        }
                        else if (dat[0] == "expquick" && dat.Length >= 3)
                        {
                            int           bx      = Utilities.StringToInt(dat[1]);
                            int           by      = Utilities.StringToInt(dat[2]);
                            int           sz      = Chunk.CHUNK_SIZE * BlockImageManager.TexWidth;
                            StringBuilder content = new StringBuilder();
                            content.Append("<!doctype html>\n<html>\n<head>\n<title>Voxalia EXP-QUICK</title>\n</head>\n<body>\n");
                            const int SIZE = 6;
                            for (int x = -SIZE; x <= SIZE; x++)
                            {
                                for (int y = -SIZE; y <= SIZE; y++)
                                {
                                    content.Append("<img style=\"position:absolute;top:" + (y + SIZE) * sz + "px;left:" + (x + SIZE) * sz + "px;\" src=\"/map/region/"
                                                   + region + "/full_img/" + (bx + x) + "/" + (by + y) + ".png\" width=\"" + sz + "\" height=\"" + sz + "\" />");
                                }
                            }
                            content.Append("\n</body>\n</html>\n");
                            http_response_content = FileHandler.encoding.GetBytes(content.ToString());
                            return;
                        }
                        else if (dat[0] == "expquick_angle" && dat.Length >= 4)
                        {
                            int           bx      = Utilities.StringToInt(dat[1]);
                            int           by      = Utilities.StringToInt(dat[2]);
                            int           bz      = Utilities.StringToInt(dat[3]);
                            int           sz      = Chunk.CHUNK_SIZE * BlockImageManager.TexWidth;
                            int           sz2     = Chunk.CHUNK_SIZE * BlockImageManager.TexWidth2;
                            StringBuilder content = new StringBuilder();
                            content.Append("<!doctype html>\n<html>\n<head>\n<title>Voxalia EXP-QUICK (Angled)</title>\n</head>\n<body>\n");
                            const int SIZE = 3;
                            for (int x = -SIZE; x <= SIZE; x++)
                            {
                                for (int y = -SIZE; y <= SIZE; y++)
                                {
                                    for (int z = -SIZE; z <= SIZE; z++)
                                    {
                                        int x1 = (x) * sz;
                                        int y1 = (y) * sz;
                                        int z1 = (bz + z) * sz;
                                        int xw = (SIZE * 2 * sz) + (x1 - y1);
                                        int yw = ((SIZE * 2 * sz) + ((x1 + y1) - (z1))) / 2;
                                        content.Append("<img style=\"position:absolute;top:" + yw + "px;left:" + xw + "px;z-index:" + z + ";\" src=\"/map/region/"
                                                       + region + "/full_img_angle/" + (bx + x) + "/" + (by + y) + "/" + (bz + z) + ".png\" width=\"" + sz2 + "\" height=\"" + sz2 + "\" />");
                                    }
                                }
                            }
                            content.Append("\n</body>\n</html>\n");
                            http_response_content = FileHandler.encoding.GetBytes(content.ToString());
                            return;
                        }
                        break;
                    }
                }
            }
            else
#endif
            if (pageLow.StartsWith("/log_view/"))
            {
                string[]      dat      = pageLow.Substring("/log_view/".Length).SplitFast('/');
                string        username = dat[0];
                string        passcode = dat.Length < 2 ? "" : dat[1];
                bool          valid    = false;
                StringBuilder content  = new StringBuilder();
                content.Append("<!doctype html>\n<html>\n<head>\n<title>Voxalia Log View</title>\n</head>\n<body>\n");
                lock (TheServer.TickLock)
                {
                    FDSSection cfg = TheServer.GetPlayerConfig(username);
                    valid = cfg != null &&
                            cfg.GetString("web.is_admin", "false").ToLowerFast() == "true" &&
                            cfg.GetString("web.passcode", "") == Utilities.HashQuick(username.ToLowerFast(), passcode);
                }
                if (valid)
                {
                    content.Append("Logs follow:\n<pre><code>\n");
                    lock (TheServer.RecentMessagesLock)
                    {
                        foreach (string str in TheServer.RecentMessages)
                        {
                            foreach (string substr in str.SplitFast('\n'))
                            {
                                string trimmedsubstr = substr.Trim();
                                if (trimmedsubstr.Length > 0)
                                {
                                    content.Append(trimmedsubstr.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;")).Append("\n");
                                }
                            }
                        }
                    }
                    content.Append("\n</code></pre>");
                }
                else
                {
                    content.Append("Not a valid login!");
                }
                content.Append("\n</body>\n</html>\n");
                http_response_content = FileHandler.encoding.GetBytes(content.ToString());
                return;
            }
            Do404();
        }
Esempio n. 38
0
 /// <summary>
 /// Initializes a new instance of <see cref="VertexBufferProperties"/> class.
 /// </summary>
 /// <param name="inputCount">The number of inputs to the vertex shader.</param>
 /// <param name="usage">Indicates how frequently the vertex buffer is likely to be updated.</param>
 /// <param name="data">The initial contents of the vertex buffer</param>
 public VertexBufferProperties(int inputCount, VertexUsage usage, DataStream data)
 {
     InputCount = inputCount;
     Usage      = usage;
     Data       = data;
 }
Esempio n. 39
0
 public virtual void Deserialize(DataStream reader)
 {
 }
Esempio n. 40
0
 public virtual void Serialize(DataStream writer)
 {
     //no need to implement as this is a response
 }
Esempio n. 41
0
        public static void PackBlock(byte[] src, int offset, int length, DataStream ds)
        {
            int histLength = 0;

            PackBlock(src, offset, length, ds, ref histLength);
        }
Esempio n. 42
0
 public override void Encode(byte[] src, int offset, int length, DataStream ds)
 {
     PackBlock(src, offset, length, ds, ref HistoryLength);
 }
        public AntennaMesh(string lable, Point3D[] points, Color color)
        {
            Lable = lable;
            Color = color;

            vertexStride            = Marshal.SizeOf(typeof(PositionColoredVertex)); // 16 bytes
            numVertices             = points.Length;
            vertexBufferSizeInBytes = vertexStride * numVertices;

            vertices = new DataStream(vertexBufferSizeInBytes, true, true);


            float a, b, c;
            int   arbgColor = ToArbg(color);

            for (int i = 0; i < numVertices; i++)
            {
                a = Convert.ToSingle(points[i].X);
                b = Convert.ToSingle(points[i].Y);
                c = Convert.ToSingle(points[i].Z);
                vertices.Write(new PositionColoredVertex(a, c, b, arbgColor));
            }

            vertices.Position = 0;

            vertexBuffer = new SharpDX.Direct3D11.Buffer(
                DeviceManager.Instance.device,
                vertices,
                vertexBufferSizeInBytes,
                ResourceUsage.Default,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            numIndices             = numVertices;
            indexStride            = Marshal.SizeOf(typeof(short)); // 2 bytes
            indexBufferSizeInBytes = numIndices * indexStride;

            indices = new DataStream(indexBufferSizeInBytes, true, true);

            for (int i = 0; i < numIndices; i++)
            {
                indices.Write((short)i);
                //short d1 = (short)(Convert.ToDouble(P1[i]) - 1);
                //short d2 = (short)(Convert.ToDouble(P2[i]) - 1);
                //short d3 = (short)(Convert.ToDouble(P3[i]) - 1);

                ////прямая сторона
                //indices.WriteRange(new short[] { d1, d2, d3 });
                //////обратная сторона
                //indices.WriteRange(new short[] { d1, d3, d2 });
            }

            indices.Position = 0;

            indexBuffer = new SharpDX.Direct3D11.Buffer(
                DeviceManager.Instance.device,
                indices,
                indexBufferSizeInBytes,
                ResourceUsage.Default,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);
        }
        public AntennaMesh(string lable, List <double> x, List <double> y, List <double> z, List <int> P1, List <int> P2, List <int> P3, Color color, double diagSize)
        {
            Lable    = lable;
            Color    = color;
            DiagSize = diagSize;

            vertexStride            = Marshal.SizeOf(typeof(PositionColoredVertex)); // 16 bytes
            numVertices             = x.Count;
            vertexBufferSizeInBytes = vertexStride * numVertices;

            vertices = new DataStream(vertexBufferSizeInBytes, true, true);


            float a, b, c;
            int   arbgColor = ToArbg(color);;

            for (int i = 0; i < x.Count; i++)
            {
                a = Convert.ToSingle(x[i]);
                b = Convert.ToSingle(y[i]);
                c = Convert.ToSingle(z[i]);
                vertices.Write(new PositionColoredVertex(new Vector3(a, c, b), arbgColor));
            }

            vertices.Position = 0;

            vertexBuffer = new SharpDX.Direct3D11.Buffer(
                DeviceManager.Instance.device,
                vertices,
                vertexBufferSizeInBytes,
                ResourceUsage.Default,
                BindFlags.VertexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);

            numIndices             = P1.Count * 6;
            indexStride            = Marshal.SizeOf(typeof(short)); // 2 bytes
            indexBufferSizeInBytes = numIndices * indexStride;

            indices = new DataStream(indexBufferSizeInBytes, true, true);

            for (int i = 0; i < P1.Count; i++)
            {
                short d1 = (short)(Convert.ToDouble(P1[i]) - 1);
                short d2 = (short)(Convert.ToDouble(P2[i]) - 1);
                short d3 = (short)(Convert.ToDouble(P3[i]) - 1);

                //прямая сторона
                indices.WriteRange(new short[] { d1, d2, d3 });
                ////обратная сторона
                indices.WriteRange(new short[] { d1, d3, d2 });
            }

            indices.Position = 0;

            indexBuffer = new SharpDX.Direct3D11.Buffer(
                DeviceManager.Instance.device,
                indices,
                indexBufferSizeInBytes,
                ResourceUsage.Default,
                BindFlags.IndexBuffer,
                CpuAccessFlags.None,
                ResourceOptionFlags.None,
                0);
        }
        public DX11IndexedGeometry Cylinder(Cylinder settings)
        {
            float radius1 = settings.Radius1;
            float radius2 = settings.Radius2;
            float cycles  = settings.Cycles;
            float length  = settings.Length;
            int   resX    = settings.ResolutionX;
            int   resY    = settings.ResolutionY;
            bool  caps    = settings.Caps;

            DX11IndexedGeometry geom = new DX11IndexedGeometry(context);

            geom.Tag           = settings;
            geom.PrimitiveType = settings.PrimitiveType;

            int vcount = resX * (resY + 1);
            int icount = vcount * 6;

            if (caps)
            {
                //Add vertices (+1 for center)
                vcount += (resX + 1 * 2);

                //Add Triangles (on each side
                icount += (resX * 6);
            }

            float lenstart = settings.CenterY ? -length * 0.5f : 0.0f; //Start at half bottom if centered
            float lenstep  = (float)length / (float)resY;

            float y = lenstart;

            List <Pos4Norm3Tex2Vertex> verts = new List <Pos4Norm3Tex2Vertex>();
            List <int> inds = new List <int>();

            float phi = 0.0f;
            float inc = Convert.ToSingle((Math.PI * 2.0 * cycles) / (double)resX);

            float fres = Convert.ToSingle(resY);

            float fy = resY;

            #region Add Vertices tube
            for (int i = 0; i < resY + 1; i++)
            {
                float ystep = (float)i / fres;

                float radius = Map(ystep, 0, 1, radius1, radius2);

                for (int j = 0; j < resX; j++)
                {
                    float x = Convert.ToSingle(radius1 * Math.Cos(phi)) * radius;
                    float z = Convert.ToSingle(radius1 * Math.Sin(phi)) * radius;

                    Pos4Norm3Tex2Vertex v = new Pos4Norm3Tex2Vertex();
                    v.Position = new Vector4(x, y, z, 1.0f);
                    v.Normals  = new Vector3(x, 0.0f, z);
                    v.Normals.Normalize();
                    v.TexCoords = new Vector2((float)j / (float)resX, 1.0f - (float)i / fy);

                    verts.Add(v);

                    phi += inc;
                }
                y  += lenstep;
                phi = 0.0f;
            }
            #endregion

            #region Add Indices Tube
            int indstart;
            for (int i = 0; i < resY; i++)
            {
                indstart = resX * i;
                int j;
                for (j = 0; j < resX - 1; j++)
                {
                    inds.Add(indstart + j);
                    inds.Add(indstart + resX + j);
                    inds.Add(indstart + j + 1);


                    inds.Add(indstart + j + 1);
                    inds.Add(indstart + j + resX);
                    inds.Add(indstart + j + resX + 1);
                }

                inds.Add(indstart + j);
                inds.Add(indstart + resX + j);
                inds.Add(indstart);

                inds.Add(indstart + j + resX);
                inds.Add(indstart + resX);
                inds.Add(indstart);
            }

            if (caps)
            {
                indstart = verts.Count;
                y        = -length * 0.5f;

                Pos4Norm3Tex2Vertex v = new Pos4Norm3Tex2Vertex();
                v.Position = new Vector4(0, y, 0, 1.0f);
                v.Normals  = new Vector3(0.0f, -1.0f, 0.0f);
                v.Normals.Normalize();
                verts.Add(v);

                phi = 0.0f;

                for (int j = 0; j < resX; j++)
                {
                    float x = Convert.ToSingle(radius1 * Math.Cos(phi)) * radius1;
                    float z = Convert.ToSingle(radius1 * Math.Sin(phi)) * radius1;

                    v.Position = new Vector4(x, y, z, 1.0f);
                    verts.Add(v);

                    phi += inc;
                }

                for (int j = 1; j < resX + 1; j++)
                {
                    inds.Add(indstart);
                    inds.Add(indstart + j);

                    if (j == resX)
                    {
                        inds.Add(indstart + 1);
                    }
                    else
                    {
                        inds.Add(indstart + j + 1);
                    }
                }

                indstart += (resX + 1);
                y         = length * 0.5f;

                v          = new Pos4Norm3Tex2Vertex();
                v.Position = new Vector4(0, y, 0, 1.0f);
                v.Normals  = new Vector3(0.0f, 1.0f, 0.0f);
                v.Normals.Normalize();
                verts.Add(v);

                phi = 0.0f;

                for (int j = 0; j < resX; j++)
                {
                    float x = Convert.ToSingle(radius1 * Math.Cos(phi)) * radius2;
                    float z = Convert.ToSingle(radius1 * Math.Sin(phi)) * radius2;

                    v.Position = new Vector4(x, y, z, 1.0f);
                    verts.Add(v);

                    phi += inc;
                }

                for (int j = 1; j < resX + 1; j++)
                {
                    inds.Add(indstart + j);
                    inds.Add(indstart);


                    if (j == resX)
                    {
                        inds.Add(indstart + 1);
                    }
                    else
                    {
                        inds.Add(indstart + j + 1);
                    }
                }
            }
            #endregion

            DataStream ds = new DataStream(verts.Count * Pos4Norm3Tex2Vertex.VertexSize, true, true);
            ds.Position = 0;
            ds.WriteRange(verts.ToArray());
            ds.Position = 0;


            var vbuffer = new SlimDX.Direct3D11.Buffer(context.Device, ds, new BufferDescription()
            {
                BindFlags      = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags    = ResourceOptionFlags.None,
                SizeInBytes    = (int)ds.Length,
                Usage          = ResourceUsage.Default
            });

            ds.Dispose();

            var indexstream = new DataStream(inds.Count * 4, true, true);
            indexstream.WriteRange(inds.ToArray());
            indexstream.Position = 0;

            geom.VertexBuffer  = vbuffer;
            geom.IndexBuffer   = new DX11IndexBuffer(context, indexstream, false, true);
            geom.InputLayout   = Pos4Norm3Tex2Vertex.Layout;
            geom.Topology      = PrimitiveTopology.TriangleList;
            geom.VerticesCount = vcount;
            geom.VertexSize    = Pos4Norm3Tex2Vertex.VertexSize;

            //Since cylinder can be a cone, max box is max of radius
            float maxrad = radius1 > radius2 ? radius1 : radius2;

            geom.HasBoundingBox = true;
            geom.BoundingBox    = new BoundingBox(new Vector3(-maxrad, -lenstart, -maxrad), new Vector3(maxrad, lenstart, maxrad));

            return(geom);
        }
        private static void TestManagedDXDevice()
        {
            Device          device;
            SwapChain       swapChain;
            ShaderSignature inputSignature;
            VertexShader    vertexShader;
            PixelShader     pixelShader;

            var form        = new RenderForm("Tutorial 3: Simple Triangle");
            var description = new SwapChainDescription()
            {
                BufferCount       = 2,
                Usage             = Usage.RenderTargetOutput,
                OutputHandle      = form.Handle,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                SampleDescription = new SampleDescription(1, 0),
                Flags             = SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, description, out device, out swapChain);

            // create a view of our render target, which is the backbuffer of the swap chain we just created
            RenderTargetView renderTarget;

            using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                renderTarget = new RenderTargetView(device, resource);

            // setting a viewport is required if you want to actually see anything
            var context  = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height);

            context.OutputMerger.SetTargets(renderTarget);
            context.Rasterizer.SetViewports(viewport);

            // load and compile the vertex shader
            using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "VShader", "vs_4_0", ShaderFlags.None, EffectFlags.None))
            {
                inputSignature = ShaderSignature.GetInputSignature(bytecode);
                vertexShader   = new VertexShader(device, bytecode);
            }

            // load and compile the pixel shader
            using (var bytecode = ShaderBytecode.CompileFromFile("triangle.fx", "PShader", "ps_4_0", ShaderFlags.None, EffectFlags.None))
                pixelShader = new PixelShader(device, bytecode);

            // create test vertex data, making sure to rewind the stream afterward
            var vertices = new DataStream(12 * 3, true, true);

            vertices.Write(new Vector3(0.0f, 0.5f, 0.5f));
            vertices.Write(new Vector3(0.5f, -0.5f, 0.5f));
            vertices.Write(new Vector3(-0.5f, -0.5f, 0.5f));
            vertices.Position = 0;

            // create the vertex layout and buffer
            var elements     = new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0) };
            var layout       = new InputLayout(device, inputSignature, elements);
            var vertexBuffer = new SlimDX.Direct3D11.Buffer(device, vertices, 12 * 3, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

            // configure the Input Assembler portion of the pipeline with the vertex data
            context.InputAssembler.InputLayout       = layout;
            context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, 12, 0));

            // set the shaders
            context.VertexShader.Set(vertexShader);
            context.PixelShader.Set(pixelShader);

            // prevent DXGI handling of alt+enter, which doesn't work properly with Winforms
            using (var factory = swapChain.GetParent <Factory>())
                factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAltEnter);

            // handle alt+enter ourselves
            form.KeyDown += (o, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    swapChain.IsFullScreen = !swapChain.IsFullScreen;
                }
            };

            // handle form size changes
            form.UserResized += (o, e) =>
            {
                renderTarget.Dispose();

                swapChain.ResizeBuffers(2, 0, 0, Format.R8G8B8A8_UNorm, SwapChainFlags.AllowModeSwitch);
                using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0))
                    renderTarget = new RenderTargetView(device, resource);

                context.OutputMerger.SetTargets(renderTarget);
            };

            MessagePump.Run(form, () =>
            {
                // clear the render target to a soothing blue
                context.ClearRenderTargetView(renderTarget, new Color4(0.5f, 0.5f, 1.0f));

                // draw the triangle
                context.Draw(3, 0);
                swapChain.Present(0, PresentFlags.None);
            });

            // clean up all resources
            // anything we missed will show up in the debug output
            vertices.Close();
            vertexBuffer.Dispose();
            layout.Dispose();
            inputSignature.Dispose();
            vertexShader.Dispose();
            pixelShader.Dispose();
            renderTarget.Dispose();
            swapChain.Dispose();
            device.Dispose();
        }
Esempio n. 47
0
 public override void Write(DataStream strOut)
 {
     throw new NotImplementedException();
 }
Esempio n. 48
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SoundEffect"/> class.
        /// </summary>
        /// <param name="audioManager">The associated audio manager instance.</param>
        /// <param name="name">The name of the current instance.</param>
        /// <param name="waveFormat">The format of the current instance.</param>
        /// <param name="buffer">The buffer containing audio data.</param>
        /// <param name="decodedPacketsInfo">The information regaring decoded packets.</param>
        internal SoundEffect(AudioManager audioManager, string name, WaveFormat waveFormat, DataStream buffer, uint[] decodedPacketsInfo)
        {
            AudioManager = audioManager;
            Name         = name;
            Format       = waveFormat;
            AudioBuffer  = new AudioBuffer
            {
                Stream     = buffer,
                AudioBytes = (int)buffer.Length,
                Flags      = BufferFlags.EndOfStream,
            };
            LoopedAudioBuffer = new AudioBuffer
            {
                Stream     = buffer,
                AudioBytes = (int)buffer.Length,
                Flags      = BufferFlags.EndOfStream,
                LoopCount  = AudioBuffer.LoopInfinite,
            };

            DecodedPacketsInfo = decodedPacketsInfo;

            Duration = Format.SampleRate > 0 ? TimeSpan.FromMilliseconds(GetSamplesDuration() * 1000 / Format.SampleRate) : TimeSpan.Zero;

            children  = new List <WeakReference>();
            VoicePool = AudioManager.InstancePool.GetVoicePool(Format);
        }
Esempio n. 49
0
 public M2(DataStream data) : base(data)
 {
     V4 = data.GetBool();
 }
Esempio n. 50
0
        /// <summary>
        /// Converts a NodeContainerFormat into a BinaryFormat.
        /// </summary>
        /// <param name="source">Input format.</param>
        /// <returns>The node container format.</returns>
        /// <exception cref="ArgumentNullException">Thrown if source is null.</exception>
        public virtual BinaryFormat Convert(NodeContainerFormat source)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // Reorder nodes
            source.Root.SortChildren((x, y) =>
                                     string.CompareOrdinal(x.Name.ToLowerInvariant(), y.Name.ToLowerInvariant()));

            // Fill node indexes
            FillNodeIndexes(source.Root);

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            DataStream stream = _writerParameters.OutputStream ?? DataStreamFactory.FromMemory();

            stream.Position = 0;

            var writer = new DataWriter(stream)
            {
                DefaultEncoding = Encoding.GetEncoding(1252),
                Endianness      = _writerParameters.Endianness == Endianness.LittleEndian
                    ? EndiannessMode.LittleEndian
                    : EndiannessMode.BigEndian,
            };

            var  directories = new List <Node>();
            var  files       = new List <Node>();
            uint fileOffset  = 0;
            uint maxFileSize = 0;

            foreach (Node node in Navigator.IterateNodes(source.Root))
            {
                if (!node.IsContainer)
                {
                    uint compressedSize = (uint)node.Stream.Length;
                    fileOffset = RoundSize(fileOffset, compressedSize);
                    if (compressedSize > maxFileSize)
                    {
                        maxFileSize = compressedSize;
                    }

                    files.Add(node);
                }
                else
                {
                    directories.Add(node);
                }
            }

            if (maxFileSize >= 0xFFFFFFFF)
            {
                throw new FormatException("Can not add files over 4GB");
            }

            var header = new FileHeader
            {
                Magic        = "PARC",
                PlatformId   = _writerParameters.PlatformId,
                Endianness   = _writerParameters.Endianness,
                SizeExtended = 0,
                Relocated    = 0,
                Version      = _writerParameters.Version,
                Size         = 0,
            };

            uint directoryStartOffset = (uint)(0x20 + (0x40 * (directories.Count + files.Count)));
            uint fileStartOffset      = (uint)(directoryStartOffset + (0x20 * directories.Count));
            var  index = new ParIndex
            {
                DirectoryCount       = (uint)directories.Count,
                DirectoryStartOffset = directoryStartOffset,
                FileCount            = (uint)files.Count,
                FileStartOffset      = fileStartOffset,
            };

            uint headerSize = RoundSize((uint)((0x20 * files.Count) + fileStartOffset));

            writer.Stream.SetLength(RoundSize(fileOffset + headerSize));

            uint currentOffset = headerSize;

            if (_writerParameters.WriteDataSize)
            {
                header.Size = headerSize + fileOffset;
            }

            writer.WriteOfType(header);
            writer.WriteOfType(index);

            for (int i = 0; i < directories.Count; i++)
            {
                Node node = directories[i];
                writer.Write(node.Name, 0x40, false);

                long returnPosition = writer.Stream.Position;
                _ = writer.Stream.Seek(directoryStartOffset + (i * 0x20), System.IO.SeekOrigin.Begin);

                var directoryInfo = new ParDirectoryInfo
                {
                    SubdirectoryCount      = (uint)node.Tags["SubdirectoryCount"],
                    SubdirectoryStartIndex = (uint)node.Tags["SubdirectoryStartIndex"],
                    FileCount      = (uint)node.Tags["FileCount"],
                    FileStartIndex = (uint)node.Tags["FileStartIndex"],
                    RawAttributes  = (uint)node.Tags["RawAttributes"],
                };

                writer.WriteOfType(directoryInfo);
                writer.WritePadding(0x00, 0x20);

                _ = writer.Stream.Seek(returnPosition, System.IO.SeekOrigin.Begin);
            }

            for (int i = 0; i < files.Count; i++)
            {
                Node node = files[i];
                writer.Write(node.Name, 0x40, false);

                long returnPosition = writer.Stream.Position;
                _ = writer.Stream.Seek(fileStartOffset + (i * 0x20), System.IO.SeekOrigin.Begin);

                ParFile file = node.GetFormatAs <ParFile>();
                currentOffset                = RoundOffset(currentOffset, file.FileInfo.CompressedSize);
                file.FileInfo.DataOffset     = currentOffset;
                file.FileInfo.ExtendedOffset = 0;

                if (node.Tags.ContainsKey("RawAttributes"))
                {
                    file.FileInfo.RawAttributes = node.Tags["RawAttributes"];
                }
                else if (node.Tags.ContainsKey("FileInfo"))
                {
                    FileInfo info = node.Tags["FileInfo"];
                    file.FileInfo.RawAttributes = (uint)info.Attributes;
                }
                else
                {
                    file.FileInfo.RawAttributes = 0x20;
                }

                if (node.Tags.ContainsKey("Timestamp"))
                {
                    file.FileInfo.Timestamp = node.Tags["Timestamp"];
                }
                else if (node.Tags.ContainsKey("FileInfo"))
                {
                    DateTime baseDate = new DateTime(1970, 1, 1);
                    FileInfo info     = node.Tags["FileInfo"];
                    file.FileInfo.Timestamp = (uint)(info.LastWriteTime - baseDate).TotalSeconds;
                }
                else
                {
                    DateTime baseDate = new DateTime(1970, 1, 1);
                    file.FileInfo.Timestamp = (uint)(DateTime.Now - baseDate).TotalSeconds;
                }

                writer.WriteOfType(file.FileInfo);

                _ = writer.Stream.Seek(currentOffset, SeekOrigin.Begin);
                node.Stream.WriteTo(writer.Stream);

                currentOffset += file.FileInfo.CompressedSize;

                _ = writer.Stream.Seek(returnPosition, System.IO.SeekOrigin.Begin);
            }

            return(new BinaryFormat(stream));
        }
Esempio n. 51
0
        public unsafe void tBitmap24ToGraphicsStreamX8R8G8B8(BitmapUtil.BITMAPINFOHEADER *pBITMAPINFOHEADER, DataStream ds, int nWidth, int nHeight)
        {
            int nBmpWidth    = pBITMAPINFOHEADER->biWidthビットマップの幅dot;
            int nBmpHeight   = pBITMAPINFOHEADER->biHeightビットマップの高さdot;
            int nBmpLineByte = (nBmpWidth * 3) + ((4 - ((nBmpWidth * 3) % 4)) % 4);

            uint *pTexture = (uint *)ds.DataPointer.ToPointer();
            byte *pBitmap  = (byte *)(pBITMAPINFOHEADER + 1);

            for (int i = 0; i < nBmpHeight; i++)
            {
                if (i >= nHeight)
                {
                    break;
                }

                for (int j = 0; j < nBmpWidth; j++)
                {
                    if (j >= nWidth)
                    {
                        break;
                    }

                    uint B = *((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 0);
                    uint G = *((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 1);
                    uint R = *((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 2);
                    *(pTexture + (i * nWidth) + j) = (R << 16) | (G << 8) | B;
                }
            }
        }
Esempio n. 52
0
        private ModelData.MeshPart Process(ModelData.Mesh mesh, Assimp.Mesh assimpMesh)
        {
            var meshPart = new ModelData.MeshPart()
            {
                MaterialIndex     = assimpMesh.MaterialIndex,
                VertexBufferRange = new ModelData.BufferRange()
                {
                    Slot = mesh.VertexBuffers.Count
                },
                IndexBufferRange = new ModelData.BufferRange()
                {
                    Slot = mesh.IndexBuffers.Count
                }
            };

            var vertexBuffer = new ModelData.VertexBuffer()
            {
                Layout = new List <VertexElement>()
            };

            mesh.VertexBuffers.Add(vertexBuffer);

            var indexBuffer = new ModelData.IndexBuffer();

            mesh.IndexBuffers.Add(indexBuffer);

            var layout = vertexBuffer.Layout;

            int vertexBufferElementSize = 0;

            // Add position
            layout.Add(VertexElement.PositionTransformed(Format.R32G32B32_Float, 0));
            vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector3>();

            // Add normals
            if (assimpMesh.HasNormals)
            {
                layout.Add(VertexElement.Normal(0, Format.R32G32B32_Float, vertexBufferElementSize));
                vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector3>();
            }

            // Add colors
            if (assimpMesh.VertexColorChannelCount > 0)
            {
                for (int localIndex = 0, i = 0; i < assimpMesh.VertexColorChannelCount; i++)
                {
                    if (assimpMesh.HasVertexColors(i))
                    {
                        layout.Add(VertexElement.Color(localIndex, Format.R32G32B32A32_Float, vertexBufferElementSize));
                        vertexBufferElementSize += Utilities.SizeOf <SharpDX.Color4>();
                        localIndex++;
                    }
                }
            }

            // Add textures
            if (assimpMesh.TextureCoordsChannelCount > 0)
            {
                for (int localIndex = 0, i = 0; i < assimpMesh.TextureCoordsChannelCount; i++)
                {
                    if (assimpMesh.HasTextureCoords(i))
                    {
                        var uvCount = assimpMesh.GetUVComponentCount(i);

                        if (uvCount == 2)
                        {
                            layout.Add(VertexElement.TextureCoordinate(localIndex, Format.R32G32_Float, vertexBufferElementSize));
                            vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector2>();
                        }
                        else if (uvCount == 3)
                        {
                            layout.Add(VertexElement.TextureCoordinate(localIndex, Format.R32G32B32_Float, vertexBufferElementSize));
                            vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector3>();
                        }
                        else
                        {
                            throw new InvalidOperationException("Unexpected uv count");
                        }

                        localIndex++;
                    }
                }
            }

            // Add tangent / bitangent
            if (assimpMesh.HasTangentBasis)
            {
                layout.Add(VertexElement.Tangent(Format.R32G32B32_Float, vertexBufferElementSize));
                vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector3>();

                layout.Add(VertexElement.BiTangent(Format.R32G32B32_Float, vertexBufferElementSize));
                vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector3>();
            }

            // Extract Skinning Indices / Weights
            bool hasWeights      = false;
            var  skinningCount   = new int[assimpMesh.VertexCount];
            var  skinningIndices = new Int4[assimpMesh.VertexCount];
            var  skinningWeights = new Vector4[assimpMesh.VertexCount];

            if (assimpMesh.HasBones)
            {
                meshPart.BoneOffsetMatrices = new Matrix[assimpMesh.BoneCount];
                for (int i = 0; i < assimpMesh.Bones.Length; i++)
                {
                    var bone = assimpMesh.Bones[i];
                    meshPart.BoneOffsetMatrices[i] = ConvertMatrix(bone.OffsetMatrix);
                    if (bone.HasVertexWeights)
                    {
                        var boneNode  = scene.RootNode.FindNode(bone.Name);
                        var boneIndex = skinnedBones[boneNode];
                        for (int j = 0; j < bone.VertexWeightCount; j++)
                        {
                            var weights             = bone.VertexWeights[j];
                            var vertexSkinningCount = skinningCount[weights.VertexID];

                            skinningIndices[weights.VertexID][vertexSkinningCount] = boneIndex;

                            skinningWeights[weights.VertexID][vertexSkinningCount] = weights.Weight;

                            skinningCount[weights.VertexID] = ++vertexSkinningCount;
                        }

                        hasWeights = true;
                    }
                }

                if (hasWeights)
                {
                    layout.Add(VertexElement.BlendIndices(Format.R16G16B16A16_SInt, vertexBufferElementSize));
                    vertexBufferElementSize += Utilities.SizeOf <SharpDX.Int4>();

                    layout.Add(VertexElement.BlendWeights(Format.R32G32B32A32_Float, vertexBufferElementSize));
                    vertexBufferElementSize += Utilities.SizeOf <SharpDX.Vector4>();
                }
            }

            // Write all vertices
            meshPart.VertexBufferRange.Count = assimpMesh.VertexCount;
            vertexBuffer.Count  = assimpMesh.VertexCount;
            vertexBuffer.Buffer = new byte[vertexBufferElementSize * assimpMesh.VertexCount];

            // Update the MaximumBufferSizeInBytes needed to load this model
            if (vertexBuffer.Buffer.Length > model.MaximumBufferSizeInBytes)
            {
                model.MaximumBufferSizeInBytes = vertexBuffer.Buffer.Length;
            }

            var vertexStream = DataStream.Create(vertexBuffer.Buffer, true, true);

            for (int i = 0; i < assimpMesh.VertexCount; i++)
            {
                var position = assimpMesh.Vertices[i];
                vertexStream.Write(position);

                // Store bounding points for BoundingSphere pre-calculation
                boundingPoints[currentBoundingPointIndex++] = new Vector3(position.X, position.Y, position.Z);

                // Add normals
                if (assimpMesh.HasNormals)
                {
                    vertexStream.Write(assimpMesh.Normals[i]);
                }

                // Add colors
                if (assimpMesh.VertexColorChannelCount > 0)
                {
                    for (int j = 0; j < assimpMesh.VertexColorChannelCount; j++)
                    {
                        if (assimpMesh.HasVertexColors(j))
                        {
                            vertexStream.Write(assimpMesh.GetVertexColors(j)[i]);
                        }
                    }
                }

                // Add textures
                if (assimpMesh.TextureCoordsChannelCount > 0)
                {
                    for (int j = 0; j < assimpMesh.TextureCoordsChannelCount; j++)
                    {
                        if (assimpMesh.HasTextureCoords(j))
                        {
                            var uvCount = assimpMesh.GetUVComponentCount(j);

                            var uv = assimpMesh.GetTextureCoords(j)[i];

                            if (uvCount == 2)
                            {
                                vertexStream.Write(new Vector2(uv.X, uv.Y));
                            }
                            else
                            {
                                vertexStream.Write(uv);
                            }
                        }
                    }
                }

                // Add tangent / bitangent
                if (assimpMesh.HasTangentBasis)
                {
                    vertexStream.Write(assimpMesh.Tangents[i]);
                    vertexStream.Write(assimpMesh.BiTangents[i]);
                }

                // Add Skinning Indices/Weights
                if (assimpMesh.HasBones && hasWeights)
                {
                    vertexStream.Write(skinningIndices[i]);
                    vertexStream.Write(skinningWeights[i]);
                }
            }
            vertexStream.Dispose();

            // Write all indices
            var indices = assimpMesh.GetIntIndices();

            indexBuffer.Count = indices.Length;
            meshPart.IndexBufferRange.Count = indices.Length;
            if (meshPart.VertexBufferRange.Count < 65536)
            {
                // Write only short indices if count is less than the size of a short
                indexBuffer.Buffer = new byte[indices.Length * 2];
                using (var indexStream = DataStream.Create(indexBuffer.Buffer, true, true))
                    foreach (int index in indices)
                    {
                        indexStream.Write((ushort)index);
                    }
            }
            else
            {
                // Otherwise, use full 32-bit precision to store indices
                indexBuffer.Buffer = new byte[indices.Length * 4];
                using (var indexStream = DataStream.Create(indexBuffer.Buffer, true, true))
                    indexStream.WriteRange(indices);
            }

            // Update the MaximumBufferSizeInBytes needed to load this model
            if (indexBuffer.Buffer.Length > model.MaximumBufferSizeInBytes)
            {
                model.MaximumBufferSizeInBytes = indexBuffer.Buffer.Length;
            }

            return(meshPart);
        }
Esempio n. 53
0
 public override string ToString() => $"{Occurrence}x {Codepoint}: {DataStream.FromBytes(Sequence).ToHexString()}";
Esempio n. 54
0
        public unsafe void tBitmap24ToGraphicsStreamR5G6B5(BitmapUtil.BITMAPINFOHEADER *pBITMAPINFOHEADER, DataStream gs, int nWidth, int nHeight)
        {
            int nBmpWidth    = pBITMAPINFOHEADER->biWidthビットマップの幅dot;
            int nBmpHeight   = pBITMAPINFOHEADER->biHeightビットマップの高さdot;
            int nBmpLineByte = (nBmpWidth * 3) + ((4 - ((nBmpWidth * 3) % 4)) % 4);

            ushort *pTexture = (ushort *)gs.DataPointer.ToPointer();
            byte *  pBitmap  = (byte *)(pBITMAPINFOHEADER + 1);

            for (int i = 0; i < nBmpHeight; i++)
            {
                if (i >= nHeight)
                {
                    break;
                }

                for (int j = 0; j < nBmpWidth; j++)
                {
                    if (j >= nWidth)
                    {
                        break;
                    }

                    ushort B = (ushort)((*((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 0) >> 3) & 0x1f);
                    ushort G = (ushort)((*((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 1) >> 2) & 0x3f);
                    ushort R = (ushort)((*((pBitmap + (((nBmpHeight - i) - 1) * nBmpLineByte)) + (j * 3) + 2) >> 3) & 0x1f);
                    *(pTexture + (i * nWidth) + j) = (ushort)((R << 11) | (G << 5) | B);
                }
            }
        }
Esempio n. 55
0
        static void Main()
        {
            var form = new RenderForm("SlimDX - Conway's game of life Direct3D 11 Sample");
            var desc = new SwapChainDescription()
            {
                BufferCount       = 1,
                ModeDescription   = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                IsWindowed        = true,
                OutputHandle      = form.Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device    device;
            SwapChain swapChain;

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain);

            device.Factory.SetWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll);

            Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0);
            var       renderView = new RenderTargetView(device, backBuffer);
            var       bytecode   = ShaderBytecode.CompileFromFile("Render.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None);
            var       effect     = new Effect(device, bytecode);
            var       technique  = effect.GetTechniqueByIndex(0);
            var       pass       = technique.GetPassByIndex(0);
            String    errors;
            var       computeByteCode = ShaderBytecode.CompileFromFile("compute.fx", "CS", "cs_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
            var       compute         = new ComputeShader(device, computeByteCode);

            // shader variable handles
            var conwayResourceH = effect.GetVariableByName("tex").AsResource();
            var resolutionInvH  = effect.GetVariableByName("resolutionInv").AsVector();

            resolutionInvH.Set(new Vector2(1.0f / form.ClientSize.Width, 1.0f / form.ClientSize.Height));
            EffectVectorVariable lightPosSSH = effect.GetVariableByName("lightPosSS").AsVector();

            // create texture, fill it with random data
            Texture2DDescription textureDesc = new Texture2DDescription()
            {
                Width             = form.ClientSize.Width,
                Height            = form.ClientSize.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                CpuAccessFlags    = CpuAccessFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Default,
                OptionFlags       = ResourceOptionFlags.None,
                BindFlags         = BindFlags.UnorderedAccess | BindFlags.ShaderResource,
                Format            = Format.R32_Float
            };

            var random = new Random();
            var data   = new float[form.ClientSize.Width * form.ClientSize.Height];

            for (int i = 0; i < form.ClientSize.Width; ++i)
            {
                for (int j = 0; j < form.ClientSize.Height; ++j)
                {
                    data[i * form.ClientSize.Height + j] = (float)random.Next(2);
                }
            }

            DataStream    ds       = new DataStream(data, true, false);
            DataRectangle dataRect = new DataRectangle(4 * form.ClientSize.Width, ds);

            Texture2D conwayTex = new Texture2D(device, textureDesc, dataRect);

            // Create SRV and UAV over the same texture
            UnorderedAccessView conwayUAV = new UnorderedAccessView(device, conwayTex);
            ShaderResourceView  conwaySRV = new ShaderResourceView(device, conwayTex);

            // On the more typical setup where you switch shaders,
            // you will have to set the texture after every
            conwayResourceH.SetResource(conwaySRV);

            device.ImmediateContext.OutputMerger.SetTargets(renderView);
            device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
            device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip;

            Vector2 lightPosSS;
            float   angle = 0;

            MessagePump.Run(form, () =>
            {
                // this does the light rotation
                angle     += 0.002f;
                lightPosSS = new Vector2((float)Math.Sin(angle) * 0.5f + 0.5f, (float)Math.Cos(angle) * 0.5f + 0.5f);
                lightPosSSH.Set(lightPosSS);

                device.ImmediateContext.ComputeShader.Set(compute);
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(conwayUAV, 0);
                device.ImmediateContext.Dispatch(form.ClientSize.Width / 16 + 1, form.ClientSize.Height / 16 + 1, 1);

                // After running the CS you have to unset UAV from the shader, so you can use it as SRV
                device.ImmediateContext.ComputeShader.SetUnorderedAccessView(null, 0);

                device.ImmediateContext.ClearRenderTargetView(renderView, Color.Black);

                for (int i = 0; i < technique.Description.PassCount; ++i)
                {
                    pass.Apply(device.ImmediateContext);
                    // No vertices are send as they are created in the vertex shader on the fly.
                    device.ImmediateContext.Draw(4, 0);
                }

                swapChain.Present(0, PresentFlags.None);
            });

            computeByteCode.Dispose();
            conwayUAV.Dispose();
            conwaySRV.Dispose();
            conwayTex.Dispose();
            ds.Dispose();
            bytecode.Dispose();
            effect.Dispose();
            renderView.Dispose();
            backBuffer.Dispose();
            device.Dispose();
            swapChain.Dispose();
        }
Esempio n. 56
0
 public override DataStream Deserialize(DataStream ds)
 {
     WorldId = ds.ReadUInt32();
     return(base.Deserialize(ds));
 }
Esempio n. 57
0
 public override void Serialize(DataStream writer)
 {
     base.Serialize(writer);
     writer.WriteSInt32(ClientID);
 }
Esempio n. 58
0
 public override void Deserialize(DataStream reader)
 {
     base.Deserialize(reader);
     ClientID = reader.ReadSInt32();
 }
Esempio n. 59
0
        public void Run()
        {
            // --------------------------------------------------------------------------------------
            // Init Direct3D11
            // --------------------------------------------------------------------------------------

            // Create Device and SwapChain
            var device  = new Device(DriverType.Hardware, DeviceCreationFlags.None);
            var context = device.ImmediateContext;

            const int Width  = 1024;
            const int Height = 1024;
            const int Count  = 1000;

            Console.WriteLine("Texture Size: ({0},{1}) - Count: {2}", Width, Height, Width * Height);
            Console.WriteLine();

            // Create random buffer
            var   random        = new Random();
            float maxScale      = (float)((byte)random.Next());
            var   randbomBuffer = new DataStream(sizeof(float) * Width * Height, true, true);

            for (int i = 0; i < Width * Height; i++)
            {
                var value = (float)random.NextDouble();
                if (value < 0.1 || value > 0.9)
                {
                    value = value * (float)random.NextDouble() * maxScale * ((value < 0.1) ? maxScale : 1.0f);
                }
                randbomBuffer.Write(value);
            }

            // Create random 2D texture
            var texture = new Texture2D(
                device,
                new Texture2DDescription
            {
                ArraySize         = 1,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R32_Float,
                Width             = Width,
                Height            = Height,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage             = ResourceUsage.Immutable
            }, new DataRectangle(randbomBuffer.DataPointer, sizeof(float) * Width));
            var textureView = new ShaderResourceView(device, texture);

            var gpuProfiler = new GPUProfiler();

            gpuProfiler.Initialize(device);
            double elapsedTime = 0.0f;

            Console.WriteLine("Compiling Shaders...");
            Console.WriteLine();

            var pixelShaderMinMax = new MipMapMinMax();

            pixelShaderMinMax.Size = new Size(Width, Height);
            pixelShaderMinMax.Initialize(device);

            var testRunner = new Action <IMinMaxProcessor>((processor) =>
            {
                gpuProfiler.Begin(context);
                for (int i = 0; i < Count; i++)
                {
                    processor.Reduce(context, textureView);
                }
                gpuProfiler.End(context);

                context.Flush();
                float newMin;
                float newMax;
                processor.GetResults(context, out newMin, out newMax);

                elapsedTime = gpuProfiler.GetElapsedMilliseconds(context);
                Console.WriteLine("GPU {0}: {1} / {2} in {3}ms", processor, newMin, newMax, elapsedTime);
            });

            Console.WriteLine("Running Tests...");
            Console.WriteLine();

            var clock = new Stopwatch();
            var min   = float.MaxValue;
            var max   = float.MinValue;

            unsafe
            {
                var buffer = (float *)randbomBuffer.DataPointer;
                clock.Start();
                for (int j = 0; j < Count; j++)
                //for (int j = 0; j < 1; j++)
                {
                    min = float.MaxValue;
                    max = float.MinValue;
                    for (int i = 0; i < Width * Height; i++)
                    {
                        var value = buffer[i];
                        if (value < min)
                        {
                            min = value;
                        }
                        if (value > max)
                        {
                            max = value;
                        }
                    }
                }
                clock.Stop();
            }
            Console.WriteLine("CPU MinMax: {0} / {1} {2}ms", min, max, clock.ElapsedMilliseconds);


            Console.WriteLine();
            for (int i = 1; i < 4; i++)
            {
                pixelShaderMinMax.ReduceFactor = i;
                testRunner(pixelShaderMinMax);
            }

            Console.WriteLine();
        }
Esempio n. 60
0
 public override void Write(DataStream strOut)
 {
     this.data.WriteTo(strOut);
 }