Esempio n. 1
0
 protected override void Render(DeviceContext deviceContext, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix)
 {
     Context.DirectX.EnableZBuffer();
     _sky.Render(deviceContext, _camera.ViewMatrix, Context.DirectX.ProjectionMatrix, _sun ,_camera);
     _sphere.Render(deviceContext, Matrix.Scaling(100), _camera.ViewMatrix, Context.DirectX.ProjectionMatrix);
     Context.DirectX.DisableZBuffer();
 }
Esempio n. 2
0
        public FormSlices(Form1 form, Nodes nodes, DataToRender dataToRender, DeviceContext context)
        {
            this.form = form;
            this.nodes = nodes;
            this.dataToRender = dataToRender;
            InitializeComponent();

            if (!dataToRender.pathToVtk)
            {
                trackBar1.Enabled = false;
                trackBar2.Enabled = false;
                trackBar3.Enabled = false;
                checkBoxXY.Enabled = false;
                checkBoxXZ.Enabled = false;
                checkBoxYZ.Enabled = false;
                DisableOkolie();
                form.StatusInfo = "Set the path to vtk files to enable full functionality!";
            }
            else
            {
                this.SetForSlices();
            }
            checkBox1.Checked = dataToRender.okolie;
            DisableButton2();
            DisableButton3();
            SetComboBox();
        }
Esempio n. 3
0
        protected D3DApp(IntPtr hInstance)
        {
            AppInst = hInstance;
            MainWindowCaption = "D3D11 Application";
            DriverType = DriverType.Hardware;
            ClientWidth = 800;
            ClientHeight = 600;
            Enable4XMsaa = false;
            Window = null;
            AppPaused = false;
            Minimized = false;
            Maximized = false;
            Resizing = false;
            Msaa4XQuality = 0;
            Device = null;
            ImmediateContext = null;
            SwapChain = null;
            DepthStencilBuffer = null;
            RenderTargetView = null;
            DepthStencilView = null;
            Viewport = new Viewport();
            Timer = new GameTimer();

            GD3DApp = this;
        }
Esempio n. 4
0
        public D3D11RenderingPane( Factory dxgiFactory, SlimDX.Direct3D11.Device d3D11Device, DeviceContext d3D11DeviceContext, D3D11HwndDescription d3D11HwndDescription )
        {
            mDxgiFactory = dxgiFactory;
            mD3D11Device = d3D11Device;
            mD3D11DeviceContext = d3D11DeviceContext;

            var swapChainDescription = new SwapChainDescription
                                       {
                                           BufferCount = 1,
                                           ModeDescription =
                                               new ModeDescription( d3D11HwndDescription.Width,
                                                                    d3D11HwndDescription.Height,
                                                                    new Rational( 60, 1 ),
                                                                    Format.R8G8B8A8_UNorm ),
                                           IsWindowed = true,
                                           OutputHandle = d3D11HwndDescription.Handle,
                                           SampleDescription = new SampleDescription( 1, 0 ),
                                           SwapEffect = SwapEffect.Discard,
                                           Usage = Usage.RenderTargetOutput
                                       };

            mSwapChain = new SwapChain( mDxgiFactory, mD3D11Device, swapChainDescription );
            mDxgiFactory.SetWindowAssociation( d3D11HwndDescription.Handle, WindowAssociationFlags.IgnoreAll );

            CreateD3D11Resources( d3D11HwndDescription.Width, d3D11HwndDescription.Height );

            PauseRendering = false;
        }
Esempio n. 5
0
        public override WriteableBitmap Initialize(Device device)
		{
			const int width = 600;
			const int height = 400;

			// Create device and swap chain.
            var swapChainPresenter = new WpfSwapChainPresenter();
			_swapChain = device.CreateSwapChain(width, height, swapChainPresenter);

			_deviceContext = device.ImmediateContext;

			// Create RenderTargetView from the backbuffer.
			var backBuffer = Texture2D.FromSwapChain(_swapChain, 0);
			_renderTargetView = device.CreateRenderTargetView(backBuffer);

			// Create DepthStencilView.
			var depthStencilBuffer = device.CreateTexture2D(new Texture2DDescription
			{
				ArraySize = 1,
				MipLevels = 1,
				Width = width,
				Height = height,
				BindFlags = BindFlags.DepthStencil
			});
			var depthStencilView = device.CreateDepthStencilView(depthStencilBuffer);

			// Prepare all the stages.
			_deviceContext.Rasterizer.SetViewports(new Viewport(0, 0, width, height, 0.0f, 1.0f));
			_deviceContext.OutputMerger.SetTargets(depthStencilView, _renderTargetView);

            return swapChainPresenter.Bitmap;
		}
Esempio n. 6
0
        public bool Initialize(Device device, DeviceContext deviceContext, IntPtr windowHandle, int screanWidth, int screenHeight, Matrix baseViewMatrix)
        {
            // Store the screen width and height.
            ScreenWidth = screanWidth;
            ScreenHeight = screenHeight;

            // Store the base view matrix.
            BaseViewMatrix = baseViewMatrix;

            // Create the font object.
            Font = new Font();

            // Initialize the font object.
            if (!Font.Initialize(device, "fontdata.txt", "font.dds"))
                return false;

            // Create the font shader object.
            FontShader = new FontShader();

            // Initialize the font shader object.
            if (!FontShader.Initialize(device, windowHandle))
                return false;

            // Initialize the first sentence.
            if (!InitializeSentence(out sentences[0], 32, device))
                return false;

            // Now update the sentence vertex buffer with the new string information.
            if (!UpdateSentece(ref sentences[0], "Render Count:", 20, 20, 1, 1, 1, deviceContext))
                return false;

            return true;
        }
Esempio n. 7
0
        public void Render(DeviceContext dc, EffectPass pass, Matrix view, Matrix proj)
        {
            var position = Particle.Position;
            Model.World = Matrix.Translation(position);

            Model.Draw(dc, pass, view, proj);
        }
Esempio n. 8
0
        public static void Initialize(Device device, DeviceContext context)
        {
            // Create helper textures
            m_PermTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8_UNorm, 1, false);
            m_PermTexture2D = RenderTargetSet.CreateRenderTargetSet(device, 256, 256, Format.R8G8B8A8_UNorm, 1, false);
            m_GradTexture = RenderTargetSet.CreateRenderTargetSet(device, 16, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_PermGradTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_PermGrad4DTexture = RenderTargetSet.CreateRenderTargetSet(device, 256, 1, Format.R8G8B8A8_SNorm, 1, false);
            m_GradTexture4D = RenderTargetSet.CreateRenderTargetSet(device, 32, 1, Format.R8G8B8A8_SNorm, 1, false);

            m_PermTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermTexture");
            RenderTargetSet.BindNull(context);

            m_PermTexture2D.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermTexture2d");
            RenderTargetSet.BindNull(context);

            m_GradTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GenerateGradTexture");
            RenderTargetSet.BindNull(context);

            m_PermGradTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermGradTexture");
            RenderTargetSet.BindNull(context);

            m_PermGrad4DTexture.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GeneratePermGrad4dTexture");
            RenderTargetSet.BindNull(context);

            m_GradTexture4D.BindAsRenderTarget(context);
            PostEffectHelper.RenderFullscreenTriangle(context, "GenerateGradTexture4d");
            RenderTargetSet.BindNull(context);
        }
Esempio n. 9
0
        public void Draw(Device device, DeviceContext context, RenderTargetView renderTargetView)
        {
            var deviceChanged = _device != device || _context != context;
            _device = device;
            _context = context;

            if (deviceChanged)
            {
                DrawingSurfaceState.Device = _device;
                DrawingSurfaceState.Context = _context;
                DrawingSurfaceState.RenderTargetView = renderTargetView;
            }

            if (!_game.Initialized)
            {
                // Start running the game.
                _game.Run(GameRunBehavior.Asynchronous);
            }
            else if (deviceChanged)
            {
                _game.GraphicsDevice.Initialize();

                Microsoft.Xna.Framework.Content.ContentManager.ReloadGraphicsContent();

                // DeviceReset events
                _game.graphicsDeviceManager.OnDeviceReset(EventArgs.Empty);
                _game.GraphicsDevice.OnDeviceReset();
            }

            _game.GraphicsDevice.UpdateTarget(renderTargetView);
            _game.GraphicsDevice.ResetRenderTargets();
            _game.Tick();

            _host.RequestAdditionalFrame();
        }
        public override void Begin(DeviceContext Context)
        {
            base.Begin(Context);
            if (pLightBuffer.ElementsCount != Lights.Count() & Lights.Count() != 0)
            {
                maxLights = Lights.Count();
                pLightBuffer.Resize(Lights.Count());
                plStruct = new PointLightStruct[maxLights];
            }
            for (int i = 0; i < maxLights; i++)
            {
                if (Lights.Count() - 1 < i)
                    plStruct[i] = default(PointLightStruct);
                else if (Lights[i] is PointLight)
                {
                    PointLight l = Lights[i] as PointLight;
                    plStruct[i].positionView = MathHelper.ToVector3(Vector3.Transform(l.Position, Renderer.Camera.MatrixView));
                    plStruct[i].attenuationBegin = 0.1f;
                    plStruct[i].color = l.Color;
                    plStruct[i].attenuationEnd = l.Radius;
                }
            }
            pLightBuffer.FillBuffer(Renderer.Context, plStruct);
            cBuffer.FillBuffer(Context);
            Context.PixelShader.Set(GBuffer.PixelShader);

            // Set up render GBuffer render targets
            Context.OutputMerger.SetTargets(Renderer.BackBufferDepth, GBuffer.RenderTargets);
            Context.OutputMerger.DepthStencilState = mDepthState;
            Context.OutputMerger.BlendState = mGeometryBlendState;
        }
Esempio n. 11
0
        // Construction/destruction API

        /// <include file='doc\WindowsGraphics.uex' path='docs/doc[@for="WindowsGraphics.WindowsGraphics"]/*' />
        public WindowsGraphics( DeviceContext dc )
        {
            Debug.Assert( dc != null, "null dc!");         
            this.dc = dc;
            this.dc.SaveHdc();
            //this.disposeDc = false; // the dc is not owned by this object.
        }
        /****************************************************************************************************
         * 
         ****************************************************************************************************/
        public void UpdateBuffer(DeviceContext context, Matrix world, ICamera camera)
        {
            var view = camera.CreateViewMatrix();
            var projection = camera.CreateProjectionMatrix(Resolution);
            Matrices[0] = Matrix.Transpose(world);
            Matrices[1] = Matrix.Transpose(view);
            Matrices[2] = Matrix.Transpose(projection);
            Matrices[3] = Matrix.Transpose(world * view);
            Matrices[4] = Matrix.Transpose(world * view * projection);
            Matrices[5] = Matrix.Transpose(view * projection);
            Matrices[6] = Matrix.Invert(world);
            Matrices[7] = Matrix.Invert(world * view);
            Matrices[8] = Matrix.Transpose(Matrix.Identity * Matrix.Scaling(LightPosition));
            Matrices[9] = new Matrix(new float[] 
            {
                LerpTime, AbsoluteTime, Resolution.X, Resolution.Y,
                BeatTime, Lead,0,0,
                Nisse0, Nisse1, Nisse2, Nisse3,
                0,0,0,0,
            });
            if (Buffer == null)
            {
                Buffer = new Buffer(context.Device, Matrices.Length * Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
            }

            context.UpdateSubresource(Matrices, Buffer);
        }
Esempio n. 13
0
        public DeviceContextWpf(DeviceSettings settings)
        {
            Contract.Requires(settings != null);

            Settings = settings;
            LogEvent.Engine.Log(settings.ToString());

            eventHandlerList = new EventHandlerList();

            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating);
            //SwapChainDescription swapChainDesc = new SwapChainDescription
            //                                         {
            //                                             BufferCount = 1,
            //                                             ModeDescription =
            //                                                 new ModeDescription(Settings.ScreenWidth, Settings.ScreenHeight,
            //                                                                     new Rational(120, 1), Settings.Format),
            //                                             IsWindowed = true,
            //                                             OutputHandle =(new System.Windows.Interop.WindowInteropHelper(Global.Window)).Handle,
            //                                             SampleDescription = Settings.SampleDescription,
            //                                             SwapEffect = SwapEffect.Discard,
            //                                             Usage = Usage.RenderTargetOutput,
            //                                         };

            //LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreating);
            //Device.CreateWithSwapChain(DriverType.Hardware, Settings.CreationFlags, swapChainDesc, out device, out swapChain);
            device = new Device(DriverType.Hardware, Settings.CreationFlags, FeatureLevel.Level_11_0);

            //if (!Settings.IsWindowed)

            immediate = device.ImmediateContext;

            CreateTargets();
            LogEvent.Engine.Log(Resources.INFO_OE_DeviceCreated);
            device.ImmediateContext.Flush();
        }
Esempio n. 14
0
 public void Render(DeviceContext context, vsBuffer vsBuffer, psBuffer psBuffer)
 {
     foreach (Model model in models)
     {
         model.Render(context, vsBuffer, psBuffer);
     }
 }
Esempio n. 15
0
        internal ShaderPassCollection(DeviceContext context, Shader shader, ShaderTechnique technique)
        {
            _passes = new ShaderPass[technique.PassCount];

            for (int i = 0; i < _passes.Length; i++)
                _passes[i] = new ShaderPass(context, shader, shader.Effect.GetPass(technique.Handle, i), i);
        }
        private void CreateDeviceResources()
        {
            // This flag adds support for surfaces with a different color channel ordering
            // than the API default. It is required for compatibility with Direct2D.
            DeviceCreationFlags creationFlags = DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug;

            // This array defines the set of DirectX hardware feature levels this app will support.
            // Note the ordering should be preserved.
            // Don't forget to declare your application's minimum required feature level in its
            // description.  All applications are assumed to support 9.1 unless otherwise stated.

            SharpDX.Direct3D.FeatureLevel[] featureLevels = 
	        {
                SharpDX.Direct3D.FeatureLevel.Level_11_1,
		        SharpDX.Direct3D.FeatureLevel.Level_11_0,
		        SharpDX.Direct3D.FeatureLevel.Level_10_1,
		        SharpDX.Direct3D.FeatureLevel.Level_10_0,
		        SharpDX.Direct3D.FeatureLevel.Level_9_3
	        };

            // Create the Direct3D 11 API device object and a corresponding context.
            using (var defaultDevice = new SharpDX.Direct3D11.Device(SharpDX.Direct3D.DriverType.Hardware, creationFlags, featureLevels))
                _device = defaultDevice.QueryInterface<SharpDX.Direct3D11.Device1>();

            // Get Direct3D 11.1 context
            _deviceContext = ToDispose(_device.ImmediateContext.QueryInterface<SharpDX.Direct3D11.DeviceContext1>());
        }
Esempio n. 17
0
 public DX11RenderContext(Device device)
 {
     this.Device = device;
     this.immediatecontext = this.Device.ImmediateContext;
     this.immediatecontext.Dispose(); //Remove ref
     this.CurrentDeviceContext = this.immediatecontext;
 }
Esempio n. 18
0
        /// <summary>
        /// Render all objects
        /// </summary>
        public void Render( DeviceContext[] devCont )
        {
            if ( devCont.Length > 1 ) {
                int mod = devCont.Length;
                Task []renderTask= new Task[mod];

                for ( int i=0; i < mod; i++ ) {
                    renderTask[i] = new Task( ( m ) => {
                        int blockID = (int)m;

                        int size = (int)Math.Ceiling( g_Object3DList.Count / (float)mod );

                        for ( int j =size * blockID; j < size * ( blockID + 1 ); j++ ) {

                            if ( j < g_Object3DList.Count )
                                g_Object3DList[j].Render( devCont[blockID] );

                        }
                    }, i );

                    renderTask[i].Start();
                }

                // wait the threads
                for ( int i=0; i < mod; i++ ) {
                    renderTask[i].Wait();
                }
            } else {
                /// run through all meshes in mesh list
                /// and Render them
                foreach ( Object3D mesh in g_Object3DList )
                    mesh.Render( devCont[0] );
            }
        }
Esempio n. 19
0
        public Renderer(IntPtr swapChainPtr, OverlayConfig overlayConfig)
        {
            OverlayConfig = overlayConfig;

            Overlays = new List<IOverlay>();

            var swapChain = (SwapChain) swapChainPtr;
            Device = swapChain.GetDevice<Device>();
            Texture2D = swapChain.GetBackBuffer<Texture2D>(0);
            try
            {
                DeviceContext = new DeviceContext(Device);
            }
            catch (SharpDXException)
            {
                DeviceContext = Device.ImmediateContext;
            }
            TargetView = new RenderTargetView(Device, Texture2D);
            if (DeferredContext)
            {
                DeviceContext.Rasterizer.SetViewports(new ViewportF(0, 0, Texture2D.Description.Width, Texture2D.Description.Height, 0, 1));
                DeviceContext.OutputMerger.SetTargets(TargetView);
            }
            SpriteEngine = new DXSpriteRenderer(Device, DeviceContext);
            SpriteEngine?.Initialize();

            InitializeElementResources();
        }
Esempio n. 20
0
 public static void Draw(DeviceContext device)
 {
     foreach (Camera c in Cameras)
     {
         c.Draw(device);
     }
 }
Esempio n. 21
0
 internal void Draw(DeviceContext context)
 {
     foreach (PositionedObject po in positionedObjects.OrderByDescending(x => (cameraBelongsTo.Position - x.Position).LengthSquared()))
     {
         po.Draw(context);
     }
 }
Esempio n. 22
0
File: Sky.cs Progetto: ndech/Alpha
 public void Render(DeviceContext deviceContext, Matrix viewMatrix, Matrix projectionMatrix, Light light, ICamera camera)
 {
     _skydome.Render(deviceContext);
     _shader.Render(deviceContext, _skydome.IndexCount,
         Matrix.Scaling(10000) * Matrix.RotationY(MathUtil.PiOverTwo - _angle / 8), viewMatrix,
         projectionMatrix, _skydome.Texture, light, camera);
 }
Esempio n. 23
0
        public Engine(IoCContainer container)
        {
            _container = container;
            #if DEBUG_REFERENCES
            SharpDX.Configuration.EnableObjectTracking = true;
            SharpDX.Configuration.EnableReleaseOnFinalizer = true;
            #endif
            IDeviceContextService deviceContextService = _container.Resolve<IDeviceContextService>();

            _form = deviceContextService.Form;
            _context = deviceContextService.Context;

            _form.Icon = Resources.openuo;
            _form.Text = string.Format("OpenUO v{0}", new AssemblyInfo(Assembly.GetEntryAssembly()).Version);
            _form.ResizeBegin += OnResizeBegin;
            _form.ResizeEnd += OnResizeEnd;
            _form.FormClosed += OnFormClosed;

            _updateState = new UpdateState();
            _gameTime = new GameTime();
            _world = new World(container);

            container.Resolve<IConsole>().WriteLine("Testing 123");

            _config = _container.Resolve<IConfiguration>();
            _updateChain = _container.Resolve<IChain<UpdateState>>();
            _worldRenderChain = _container.Resolve<IWorldRenderChain>();
            _uiRenderChain = _container.Resolve<IUIRenderChain>();

            _screenTarget = new DrawScreenTarget(_context);

            _updateChain.Freeze();
            _worldRenderChain.Freeze();
            _uiRenderChain.Freeze();
        }
        public override void InitShaders(ref Device device)
        {
            ShaderBytecode vertexShaderByteCode =
                ShaderBytecode.CompileFromFile(@"Shader/basicShaders.hlsl", "VShader", "vs_4_0");

            ShaderBytecode pixelShaderByteCode =
                ShaderBytecode.CompileFromFile(@"Shader/basicShaders.hlsl", "PShader", "ps_4_0");

            _deviceContext = device.ImmediateContext;
            _deviceContext.VertexShader.Set(new VertexShader(device, vertexShaderByteCode));
            _deviceContext.PixelShader.Set(new PixelShader(device, pixelShaderByteCode));

            //----

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR"   , 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 16, 0),
            };

            _deviceContext.InputAssembler.InputLayout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), elements);

            Vertex[] vertices = new Vertex[]
            {
                new Vertex(0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f),
                new Vertex(0.5f, -.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f),
                new Vertex(-.5f, -.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f),
            };

            BufferDescription description = new BufferDescription(32 * 3, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);
            _vertexBuffer = Buffer.Create(device, vertices, description);
        }
Esempio n. 25
0
 public static Texture2D FromFile(DeviceContext context, string file, Usage usage, Pool pool)
 {
     using (var stream = File.OpenRead(file))
     {
         return FromStream(context, stream, usage, pool);
     }
 }
Esempio n. 26
0
 public static void RegisterDebug(DeviceContext context, string name, RenderTargetSet debuggedRT)
 {
     if (m_AvailableModes.Contains(name))
     {
         if (m_CurrentDebugSurface == name)
         {
             if (m_CurrentDebugMode == "A")
             {
                 PostEffectHelper.CopyAlpha(context, m_DebugRenderTarget, debuggedRT);
             }
             else if (m_CurrentDebugMode == "FRAC")
             {
                 PostEffectHelper.CopyFrac(context, m_DebugRenderTarget, debuggedRT);
             }
             else
             {
                 PostEffectHelper.Copy(context, m_DebugRenderTarget, debuggedRT);
             }
         }
     }
     else
     {
         m_IsUIRebuildRequired = true;
         m_AvailableModes.Add(name);
     }
 }
		public void Restore(DeviceContext context)
		{
			context.InputAssembler.PrimitiveTopology = this.topology;
			context.InputAssembler.InputLayout = this.layout;
			context.Rasterizer.SetViewports(this.viewports);
			context.Rasterizer.SetScissorRectangles(this.scissorRectangles);
			context.Rasterizer.State = this.rasterizerState;
			context.OutputMerger.SetBlendState(this.blendState, this.blendFactor, this.sampleMaskRef);
			context.OutputMerger.SetDepthStencilState(this.depthState, this.stencilRefRef);
			context.OutputMerger.SetRenderTargets(this.depthStencilView, this.renderTargetView[0]);

			context.PixelShader.Set(this.ps);
			context.PixelShader.SetConstantBuffers(0, this.psConstantBuffers);
			context.PixelShader.SetSamplers(0, this.psSamplers);
			context.PixelShader.SetShaderResources(0, this.psResources);

			context.VertexShader.Set(this.vs);
			context.VertexShader.SetConstantBuffers(0, this.vsConstantBuffers);
			context.VertexShader.SetSamplers(0, this.vsSamplers);
			context.VertexShader.SetShaderResources(0, this.vsResources);

			context.InputAssembler.SetIndexBuffer(this.ib, this.ibFormat, this.ibOffset);
			context.InputAssembler.SetVertexBuffers(0, this.vb, this.vbStride, this.vbOffset);

			this.renderTargetView[0].Dispose();
			this.depthStencilView.Dispose();
		}
 public override void ClearRenderTarget(DeviceContext context, Color4 color)
 {
     foreach (RenderTargetView view in renderTargetView)
     {
         context.ClearRenderTargetView(view, color);
     }
 }
Esempio n. 29
0
        public Minimap(Device device, DeviceContext dc, int minimapWidth, int minimapHeight, Terrain terrain, CameraBase viewCam)
        {
            _dc = dc;

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

            CreateMinimapTextureViews(device, minimapWidth, minimapHeight);

            _terrain = terrain;

            SetupOrthoCamera();
            _viewCam = viewCam;

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

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

            ScreenPosition = new Vector2(0.25f, 0.75f);
            Size = new Vector2(0.25f, 0.25f);
        }
Esempio n. 30
0
        public GraphicsDeviceService()
        {
            System.Windows.Forms.Control control = new System.Windows.Forms.Panel();

            deviceInformation = new GraphicsDeviceInformation()
            {
                GraphicsProfile = FeatureLevel.Level_11_0,
                DeviceCreationFlags = SharpDX.Direct3D11.DeviceCreationFlags.Debug,
                PresentationParameters = new PresentationParameters()
                {
                    BackBufferFormat = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                    DepthStencilFormat = DepthFormat.Depth32,
                    DepthBufferShaderResource = true,
                    BackBufferWidth = 1920,
                    BackBufferHeight = 1080,
                    IsFullScreen = false,
                    RenderTargetUsage = SharpDX.DXGI.Usage.RenderTargetOutput,
                    MultiSampleCount = MSAALevel.None,
                    DeviceWindowHandle = control
                }
            };

            FindAdapter();

            graphicsDevice = GraphicsDevice.New(deviceInformation.Adapter, deviceInformation.DeviceCreationFlags);

            renderTarget = RenderTarget2D.New(graphicsDevice, 1920, 1080, PixelFormat.B8G8R8A8.UNorm);
            graphicsDevice.Presenter = new RenderTargetGraphicsPresenter(graphicsDevice, renderTarget, DepthFormat.Depth32, false);

            dxDevice = (Device)typeof(GraphicsDevice).GetField("Device", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(GraphicsDevice);
            dxContext = (DeviceContext)typeof(GraphicsDevice).GetField("Context", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(GraphicsDevice);

            if (DeviceCreated != null)
                DeviceCreated(this, EventArgs.Empty);
        }
 public void Init(Device device, DeviceContext deviceContext)
 {
     m_sharedLightBuffer.Init(device);
     m_perObjectLightBuffer.Init(device);
     m_shadowMapSamplers.InitSamplers(device);
 }
Esempio n. 32
0
 protected override void OnBatchDraw(DeviceContext context, int batchCount)
 {
     context.Draw(3 * batchCount, 0);
 }
Esempio n. 33
0
 public void Render(DeviceContext deviceContext)
 {
     // Put the vertex and index buffers on the graphics pipeline to prepare for drawings.
     RenderBuffers(deviceContext);
 }
Esempio n. 34
0
        private bool SetShaderParameters(DeviceContext deviceContext, Matrix worldMatrix, Matrix viewMatrix, Matrix projectionMatrix, ShaderResourceView[] textures, Vector3 lightDirection, Vector4 diffuseColor)
        {
            try
            {
                #region Constant Matrix Buffer
                // Transpose the matrices to prepare them for shader.
                worldMatrix.Transpose();
                viewMatrix.Transpose();
                projectionMatrix.Transpose();

                // Lock the constant buffer so it can be written to.
                DataStream mappedResource;
                deviceContext.MapSubresource(ConstantMatrixBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out mappedResource);

                // Copy the matrices into the constant buffer.
                var matrixBuffer = new MatrixBuffer()
                {
                    world      = worldMatrix,
                    view       = viewMatrix,
                    projection = projectionMatrix
                };

                mappedResource.Write(matrixBuffer);

                // Unlock the constant buffer.
                deviceContext.UnmapSubresource(ConstantMatrixBuffer, 0);

                // Set the position of the constant buffer in the vertex shader.
                var bufferNumber = 0;

                // Finally set the constant buffer in the vertex shader with the updated values.
                deviceContext.VertexShader.SetConstantBuffer(bufferNumber, ConstantMatrixBuffer);

                // Set shader resource in the pixel shader.
                deviceContext.PixelShader.SetShaderResources(0, textures);
                #endregion

                #region Constant Light Buffer
                // Lock the light constant buffer so it can be written to.
                deviceContext.MapSubresource(ConstantLightBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out mappedResource);

                // Copy the lighting variables into the constant buffer.
                var lightBuffer = new LightBuffer()
                {
                    diffuseColor   = diffuseColor,
                    lightDirection = lightDirection,
                };

                mappedResource.Write(lightBuffer);

                // Unlock the constant buffer.
                deviceContext.UnmapSubresource(ConstantLightBuffer, 0);

                // Set the position of the light constant buffer in the pixel shader.
                bufferNumber = 0;

                // Finally set the light constant buffer in the pixel shader with the updated values.
                deviceContext.PixelShader.SetConstantBuffer(bufferNumber, ConstantLightBuffer);
                #endregion

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Esempio n. 35
0
 internal override void Render(ref DeviceContext context)
 {
     throw new System.NotImplementedException();
 }
Esempio n. 36
0
 /// <summary>
 /// Initializes a new instance of <see cref="ConvolveMatrixEffect"/> effect.
 /// </summary>
 /// <param name="context"></param>
 public ConvolveMatrix(DeviceContext context) : base(context, Effect.ConvolveMatrix)
 {
 }
        public void GenerateShadowMaps(Device device, DeviceContext deviceContext, CRenderScene renderScene)
        {
            // Store current render targets. Accourding to the function description we need to release these temporary interfaces
            DepthStencilView depthStencilRestore;

            RenderTargetView[] renderTargetRestore       = deviceContext.OutputMerger.GetRenderTargets(1, out depthStencilRestore);
            RawViewportF[]     viewPortsRestore          = deviceContext.Rasterizer.GetViewports <RawViewportF>();
            DepthStencilState  depthStenctilStateRestore = deviceContext.OutputMerger.DepthStencilState;
            RasterizerState    rasterizerRestore         = deviceContext.Rasterizer.State;

            int shadowMapSlotOffset     = 0;
            int cubeShadowMapSlotOffset = 0;

            // Unbind texture resources
            for (int i = CubeShadowMapBaseSlot; i < CubeShadowMapBaseSlot + MaxCubeShadowMaps; i++)
            {
                deviceContext.PixelShader.SetShaderResource(i, null);
            }

            for (int i = ShadowMapBaseSlot; i < ShadowMapBaseSlot + MaxShadowMaps; i++)
            {
                deviceContext.PixelShader.SetShaderResource(i, null);
            }

            // Generate shadow maps for all active lights
            foreach (CDirectionalLight directionalLight in m_directionalLights)
            {
                if (directionalLight.IsCastingShadow() && !directionalLight.NeedsShadowMapInit())
                {
                    // Init Shadow Map
                }
            }

            foreach (CPositionalLight positionalLight in m_positionalLights)
            {
                if (positionalLight.IsCastingShadow() && !positionalLight.NeedsShadowMapInit())
                {
                    if (positionalLight.IsShadowMapCube())
                    {
                        if (cubeShadowMapSlotOffset < MaxCubeShadowMaps)
                        {
                            positionalLight.GenerateShadowMaps(device, deviceContext, renderScene);
                            positionalLight.ShadowMapRegister = CubeShadowMapBaseSlot + cubeShadowMapSlotOffset;
                            deviceContext.PixelShader.SetShaderResource(CubeShadowMapBaseSlot + cubeShadowMapSlotOffset, positionalLight.GetShadowMapView());
                            cubeShadowMapSlotOffset++;
                        }
                    }
                    else
                    {
                        if (shadowMapSlotOffset < MaxShadowMaps)
                        {
                            positionalLight.GenerateShadowMaps(device, deviceContext, renderScene);
                            positionalLight.ShadowMapRegister = ShadowMapBaseSlot + shadowMapSlotOffset;
                            deviceContext.PixelShader.SetShaderResource(ShadowMapBaseSlot + shadowMapSlotOffset, positionalLight.GetShadowMapView());
                            shadowMapSlotOffset++;
                        }
                    }
                }
            }
            m_shadowMapSamplers.SetSamplers(deviceContext);

            // Restore previous render targets
            deviceContext.OutputMerger.SetRenderTargets(depthStencilRestore, renderTargetRestore);
            deviceContext.Rasterizer.SetViewports(viewPortsRestore);
            deviceContext.Rasterizer.State = rasterizerRestore;
            deviceContext.OutputMerger.DepthStencilState = depthStenctilStateRestore;

            //Dispose temporary interfaces
            depthStencilRestore?.Dispose();
            depthStenctilStateRestore?.Dispose();
            rasterizerRestore?.Dispose();

            foreach (RenderTargetView renderTargetView in renderTargetRestore)
            {
                renderTargetView?.Dispose();
            }
        }
Esempio n. 38
0
            public unsafe DCMapping(HandleRef hDC, Rectangle bounds)
            {
                if (hDC.Handle == IntPtr.Zero)
                {
                    throw new ArgumentNullException(nameof(hDC));
                }

                bool   success;
                IntPtr hOriginalClippingRegion = IntPtr.Zero;

                _translatedBounds = bounds;
                _graphics         = null;
                _dc = DeviceContext.FromHdc(hDC.Handle);
                _dc.SaveHdc();

                // Retrieve the x-coordinates and y-coordinates of the viewport origin for the specified device context.
                success = SafeNativeMethods.GetViewportOrgEx(hDC, out Point viewportOrg);
                Debug.Assert(success, "GetViewportOrgEx() failed.");

                // Create a new rectangular clipping region based off of the bounds specified, shifted over by the x & y specified in the viewport origin.
                IntPtr hClippingRegion = Gdi32.CreateRectRgn(viewportOrg.X + bounds.Left, viewportOrg.Y + bounds.Top, viewportOrg.X + bounds.Right, viewportOrg.Y + bounds.Bottom);

                Debug.Assert(hClippingRegion != IntPtr.Zero, "CreateRectRgn() failed.");

                try
                {
                    // Create an empty region oriented at 0,0 so we can populate it with the original clipping region of the hDC passed in.
                    hOriginalClippingRegion = Gdi32.CreateRectRgn(0, 0, 0, 0);
                    Debug.Assert(hOriginalClippingRegion != IntPtr.Zero, "CreateRectRgn() failed.");

                    // Get the clipping region from the hDC: result = {-1 = error, 0 = no region, 1 = success} per MSDN
                    int result = Gdi32.GetClipRgn(hDC, hOriginalClippingRegion);
                    Debug.Assert(result != -1, "GetClipRgn() failed.");

                    // Shift the viewpoint origint by coordinates specified in "bounds".
                    var lastViewPort = new Point();
                    success = SafeNativeMethods.SetViewportOrgEx(hDC, viewportOrg.X + bounds.Left, viewportOrg.Y + bounds.Top, &lastViewPort);
                    Debug.Assert(success, "SetViewportOrgEx() failed.");

                    RegionType originalRegionType;
                    if (result != 0)
                    {
                        // Get the origninal clipping region so we can determine its type (we'll check later if we've restored the region back properly.)
                        RECT originalClipRect = new RECT();
                        originalRegionType = Gdi32.GetRgnBox(hOriginalClippingRegion, ref originalClipRect);
                        Debug.Assert(originalRegionType != RegionType.ERROR, "ERROR returned from SelectClipRgn while selecting the original clipping region..");

                        if (originalRegionType == RegionType.SIMPLEREGION)
                        {
                            // Find the intersection of our clipping region and the current clipping region (our parent's)
                            //      Returns a NULLREGION, the two didn't intersect.
                            //      Returns a SIMPLEREGION, the two intersected
                            //      Resulting region (stuff that was in hOriginalClippingRegion AND hClippingRegion is placed in hClippingRegion
                            RegionType combineResult = Gdi32.CombineRgn(hClippingRegion, hClippingRegion, hOriginalClippingRegion, Gdi32.CombineMode.RGN_AND);
                            Debug.Assert((combineResult == RegionType.SIMPLEREGION) ||
                                         (combineResult == RegionType.NULLREGION),
                                         "SIMPLEREGION or NULLREGION expected.");
                        }
                    }
                    else
                    {
                        // If there was no clipping region, then the result is a simple region.
                        // We don't need to keep track of the original now, since it is empty.
                        Gdi32.DeleteObject(hOriginalClippingRegion);
                        hOriginalClippingRegion = IntPtr.Zero;
                        originalRegionType      = RegionType.SIMPLEREGION;
                    }

                    // Select the new clipping region; make sure it's a SIMPLEREGION or NULLREGION
                    RegionType selectResult = Gdi32.SelectClipRgn(hDC, hClippingRegion);
                    Debug.Assert((selectResult == RegionType.SIMPLEREGION ||
                                  selectResult == RegionType.NULLREGION),
                                 "SIMPLEREGION or NULLLREGION expected.");
                }
                catch (Exception ex) when(!ClientUtils.IsSecurityOrCriticalException(ex))
                {
                    _dc.RestoreHdc();
                    _dc.Dispose();
                }
                finally
                {
                    // Delete the new clipping region, as the clipping region for the HDC is now set
                    // to this rectangle. Hold on to hOriginalClippingRegion, as we'll need to restore
                    // it when this object is disposed.
                    success = Gdi32.DeleteObject(hClippingRegion) != BOOL.FALSE;
                    Debug.Assert(success, "DeleteObject(hClippingRegion) failed.");

                    if (hOriginalClippingRegion != IntPtr.Zero)
                    {
                        success = Gdi32.DeleteObject(hOriginalClippingRegion) != BOOL.FALSE;
                        Debug.Assert(success, "DeleteObject(hOriginalClippingRegion) failed.");
                    }
                }
            }
Esempio n. 39
0
 internal void OnDeviceReset(Device newDevice, DeviceContext newContext)
 {
     this.D3DDevice  = newDevice;
     this.D3DContext = newContext;
 }
 public void UpdatePerObjectLights(DeviceContext deviceContext, CMesh meshToRender)
 {
     // TODO henning do something smart here to get the best lights that affect this mesh
     m_perObjectLightBuffer.UpdateBuffer(deviceContext, m_positionalLights);
 }
Esempio n. 41
0
 /// <summary>
 /// Initializes a new instance of <see cref="DistantSpecular"/> effect.
 /// </summary>
 /// <param name="context"></param>
 public DistantSpecular(DeviceContext context) : base(context, Effect.DistantSpecular)
 {
 }
 internal void Init(DeviceContext deviceContext, MyRenderContextStatistics statistics)
 {
     m_deviceContext = deviceContext;
     m_statistics    = statistics;
 }
 public static MapMode SetMapMode(this DeviceContext deviceContext, MapMode mapMode) => GdiMethods.SetMapMode(deviceContext, mapMode);
        /// <summary>
        ///     Initializes the specified device.
        /// </summary>
        /// <param name="graphicsProfiles">The graphics profiles.</param>
        /// <param name="deviceCreationFlags">The device creation flags.</param>
        /// <param name="windowHandle">The window handle.</param>
        private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle)
        {
            if (nativeDevice != null)
            {
                // Destroy previous device
                ReleaseDevice();
            }

            rendererName = Adapter.NativeAdapter.Description.Description;

            // Profiling is supported through pix markers
            IsProfilingSupported = true;

            // Map GraphicsProfile to D3D11 FeatureLevel
            creationFlags = (SharpDX.Direct3D11.DeviceCreationFlags)deviceCreationFlags;

            // Default fallback
            if (graphicsProfiles.Length == 0)
            {
                graphicsProfiles = new[] { GraphicsProfile.Level_11_0, GraphicsProfile.Level_10_1, GraphicsProfile.Level_10_0, GraphicsProfile.Level_9_3, GraphicsProfile.Level_9_2, GraphicsProfile.Level_9_1 }
            }
            ;

            // Create Device D3D11 with feature Level based on profile
            for (int index = 0; index < graphicsProfiles.Length; index++)
            {
                var graphicsProfile = graphicsProfiles[index];
                try
                {
                    // D3D12 supports only feature level 11+
                    var level = graphicsProfile.ToFeatureLevel();

                    // INTEL workaround: it seems Intel driver doesn't support properly feature level 9.x. Fallback to 10.
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (level < SharpDX.Direct3D.FeatureLevel.Level_10_0)
                        {
                            level = SharpDX.Direct3D.FeatureLevel.Level_10_0;
                        }
                    }

#if STRIDE_PLATFORM_WINDOWS_DESKTOP
                    // If RenderDoc is loaded, force level 11+
                    if (GetModuleHandle("renderdoc.dll") != IntPtr.Zero)
                    {
                        if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0)
                        {
                            level = SharpDX.Direct3D.FeatureLevel.Level_11_0;
                        }
                    }
#endif

                    nativeDevice = new SharpDX.Direct3D11.Device(Adapter.NativeAdapter, creationFlags, level);

                    // INTEL workaround: force ShaderProfile to be 10+ as well
                    if (Adapter.VendorId == 0x8086)
                    {
                        if (graphicsProfile < GraphicsProfile.Level_10_0 && (!ShaderProfile.HasValue || ShaderProfile.Value < GraphicsProfile.Level_10_0))
                        {
                            ShaderProfile = GraphicsProfile.Level_10_0;
                        }
                    }

                    RequestedProfile = graphicsProfile;
                    break;
                }
                catch (Exception)
                {
                    if (index == graphicsProfiles.Length - 1)
                    {
                        throw;
                    }
                }
            }

            nativeDeviceContext = nativeDevice.ImmediateContext;
            // We keep one reference so that it doesn't disappear with InternalMainCommandList
            ((IUnknown)nativeDeviceContext).AddReference();
            if (IsDebugMode)
            {
                GraphicsResourceBase.SetDebugName(this, nativeDeviceContext, "ImmediateContext");
            }
        }
 public static bool OffsetViewportOrigin(this DeviceContext deviceContext, int x, int y) => GdiMethods.OffsetViewportOrigin(deviceContext, x, y);
 public static RegionType SelectClippingRegion(this DeviceContext deviceContext, RegionHandle region) => GdiMethods.SelectClippingRegion(deviceContext, region);
 public static bool LogicalToDevice(this DeviceContext deviceContext, params POINT[] points) => GdiMethods.LogicalToDevice(deviceContext, points);
 public static bool SetViewportExtents(this DeviceContext deviceContext, int x, int y) => GdiMethods.SetViewportExtents(deviceContext, x, y);
 public static bool SetPixel(this DeviceContext deviceContext, int x, int y, COLORREF color) => GdiMethods.SetPixel(deviceContext, x, y, color);
 public static bool SetWindowOrigin(this DeviceContext deviceContext, int x, int y) => GdiMethods.SetWindowOrigin(deviceContext, x, y);
 public static COLORREF GetPixel(this DeviceContext deviceContext, POINT point) => GdiMethods.GetPixel(deviceContext, point.x, point.y);
 public static bool DeviceToLogical(this DeviceContext deviceContext, params POINT[] points) => GdiMethods.DeviceToLogical(deviceContext, points);
 public static bool PolyBezier(this DeviceContext deviceContext, params POINT[] points)
 => GdiMethods.PolyBezier(deviceContext, points);
 public static bool SetPixel(this DeviceContext deviceContext, POINT point, COLORREF color) => GdiMethods.SetPixel(deviceContext, point.x, point.y, color);
 public static bool Ellipse(this DeviceContext deviceContext, int left, int top, int right, int bottom)
 => GdiMethods.Ellipse(deviceContext, left, top, right, bottom);
 public static COLORREF GetPixel(this DeviceContext deviceContext, int x, int y) => GdiMethods.GetPixel(deviceContext, x, y);
 public static bool InvertRectangle(this DeviceContext deviceContext, RECT rectangle)
 => GdiMethods.InvertRectangle(deviceContext, rectangle);
 public static bool RoundRectangle(this DeviceContext deviceContext, int left, int top, int right, int bottom, int cornerWidth, int cornerHeight)
 => GdiMethods.RoundRectangle(deviceContext, left, top, right, bottom, cornerWidth, cornerHeight);
 public static bool FrameRectangle(this DeviceContext deviceContext, RECT rectangle, BrushHandle brush)
 => GdiMethods.FrameRectangle(deviceContext, rectangle, brush);
 public static bool DrawFocusRectangle(this DeviceContext deviceContext, RECT rectangle)
 => GdiMethods.DrawFocusRectangle(deviceContext, rectangle);