public static void Register() {
		style = Settings.GetChoice("style");
		OnScreenInterface.Register(new OSIBossHPBar(),OnScreenInterface.LAYER_INTERFACE_SCREEN);
		
		if (style == "circular_bottomleft") {
			dss1 = new DepthStencilState {
				StencilEnable = true,
				StencilFunction = CompareFunction.Equal,
				StencilPass = StencilOperation.Increment,
				ReferenceStencil = 0,
				DepthBufferEnable = false,
			};
			bs1 = new BlendState();
			bs1.ColorWriteChannels = ColorWriteChannels.None;
			
			dss2 = new DepthStencilState {
				StencilEnable = true,
				StencilFunction = CompareFunction.NotEqual,
				StencilPass = StencilOperation.Keep,
				ReferenceStencil = 0,
				DepthBufferEnable = false,
			};
			
			rt = new RenderTarget2D(
				Config.mainInstance.graphics.GraphicsDevice,
				1920,
				96,
				false,Config.mainInstance.graphics.GraphicsDevice.DisplayMode.Format,DepthFormat.Depth24Stencil8
			);
			sb = new SpriteBatch(Config.mainInstance.graphics.GraphicsDevice);
		}
	}
		/// <summary>
		/// Creates stock states
		/// </summary>
		static DepthStencilState()
		{
			Default	= new DepthStencilState() {
				DepthEnabled		=	true,
				DepthComparison		=	ComparisonFunc.LessEqual,
				DepthWriteEnabled	=	true,
			};

			Readonly = new DepthStencilState() {
				DepthEnabled		=	true,
				DepthComparison		=	ComparisonFunc.LessEqual,
				DepthWriteEnabled	=	false,
			};

			Sky = new DepthStencilState() {
				DepthEnabled		=	true,
				DepthComparison		=	ComparisonFunc.Equal,
				DepthWriteEnabled	=	false,
			};

			None = new DepthStencilState() {
				DepthEnabled = false,
				DepthWriteEnabled = false
			};

			LightMark	=	new DepthStencilState() {
				DepthEnabled			=	true,
				DepthComparison			=	ComparisonFunc.Less,
				DepthWriteEnabled		=	false,
				StencilEnabled			=	true,
				StencilReadMask			=	0xFF,
				StencilWriteMask		=	0xFF,
				FrontFaceFailOp				=	StencilOp.Keep,
				FrontFaceDepthFailOp		=	StencilOp.Increment,
				FrontFacePassOp				=	StencilOp.Keep,		
				FrontFaceStencilComparison	=	ComparisonFunc.Always,
				BackFaceFailOp				=	StencilOp.Keep,
				BackFaceDepthFailOp			=	StencilOp.Decrement,						
				BackFacePassOp				=	StencilOp.Keep,						
				BackFaceStencilComparison	=	ComparisonFunc.Always,	
			};

			LightPass	=	new DepthStencilState() {
				DepthEnabled			=	false,
				DepthComparison			=	ComparisonFunc.Less,
				DepthWriteEnabled		=	false,
				StencilEnabled			=	true,
				StencilReadMask			=	0xFF,
				StencilWriteMask		=	0xFF,
				FrontFaceFailOp				=	StencilOp.Keep,
				FrontFaceDepthFailOp		=	StencilOp.Keep,
				FrontFacePassOp				=	StencilOp.Decrement,	
				FrontFaceStencilComparison	=	ComparisonFunc.Equal,
				BackFaceFailOp				=	StencilOp.Keep,
				BackFaceDepthFailOp			=	StencilOp.Keep,
				BackFacePassOp				=	StencilOp.Decrement,	
				BackFaceStencilComparison	=	ComparisonFunc.Equal,
			};
		}
Example #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpriteBatchState"/> structure.
 /// </summary>
 /// <param name="sortMode">The sprite batch's sort mode.</param>
 /// <param name="blendState">The sprite batch's blend state.</param>
 /// <param name="samplerState">The sprite batch's sampler state.</param>
 /// <param name="rasterizerState">The sprite batch's rasterizer state.</param>
 /// <param name="depthStencilState">The sprite batch's depth/stencil state.</param>
 /// <param name="effect">The sprite batch's custom effect.</param>
 /// <param name="transformMatrix">The sprite batch's transformation matrix.</param>
 public SpriteBatchState(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, RasterizerState rasterizerState, DepthStencilState depthStencilState, Effect effect, Matrix transformMatrix)
 {
     this.sortMode          = sortMode;
     this.blendState        = blendState;
     this.samplerState      = samplerState;
     this.rasterizerState   = rasterizerState;
     this.depthStencilState = depthStencilState;
     this.customEffect      = effect;
     this.transformMatrix   = transformMatrix;
 }
        public void Affect(GraphicsDevice device, DepthStencilState currentState)
        {
            DepthStencilState internalState = new DepthStencilState();

            // DepthBufferEnable
            internalState.DepthBufferEnable = DepthBufferEnable.HasValue ? DepthBufferEnable.Value : currentState.DepthBufferEnable;

            // DepthBufferWriteEnable
            internalState.DepthBufferWriteEnable = DepthBufferWriteEnable.HasValue ? DepthBufferWriteEnable.Value : currentState.DepthBufferWriteEnable;

            // DepthBufferFunction
            internalState.DepthBufferFunction = DepthBufferFunction.HasValue ? DepthBufferFunction.Value : currentState.DepthBufferFunction;

            // StencilEnable
            internalState.StencilEnable = StencilEnable.HasValue ? StencilEnable.Value : currentState.StencilEnable;

            // StencilFunction
            internalState.StencilFunction = StencilFunction.HasValue ? StencilFunction.Value : currentState.StencilFunction;

            // StencilPass
            internalState.StencilPass = StencilPass.HasValue ? StencilPass.Value : currentState.StencilPass;

            // StencilFail
            internalState.StencilFail = StencilFail.HasValue ? StencilFail.Value : currentState.StencilFail;

            // StencilDepthBufferFail
            internalState.StencilDepthBufferFail = StencilDepthBufferFail.HasValue ? StencilDepthBufferFail.Value : currentState.StencilDepthBufferFail;

            // TwoSidedStencilMode
            internalState.TwoSidedStencilMode = TwoSidedStencilMode.HasValue ? TwoSidedStencilMode.Value : currentState.TwoSidedStencilMode;

            // CounterClockwiseStencilFunction
            internalState.CounterClockwiseStencilFunction = CounterClockwiseStencilFunction.HasValue ? CounterClockwiseStencilFunction.Value : currentState.CounterClockwiseStencilFunction;

            // CounterClockwiseStencilPass
            internalState.CounterClockwiseStencilPass = CounterClockwiseStencilPass.HasValue ? CounterClockwiseStencilPass.Value : currentState.CounterClockwiseStencilPass;

            // CounterClockwiseStencilFail
            internalState.CounterClockwiseStencilFail = CounterClockwiseStencilFail.HasValue ? CounterClockwiseStencilFail.Value : currentState.CounterClockwiseStencilFail;

            // CounterClockwiseStencilDepthBufferFail
            internalState.CounterClockwiseStencilDepthBufferFail = CounterClockwiseStencilDepthBufferFail.HasValue ? CounterClockwiseStencilDepthBufferFail.Value : currentState.CounterClockwiseStencilDepthBufferFail;

            // StencilMask
            internalState.StencilMask = StencilMask.HasValue ? StencilMask.Value : currentState.StencilMask;

            // StencilWriteMask
            internalState.StencilWriteMask = StencilWriteMask.HasValue ? StencilWriteMask.Value : currentState.StencilWriteMask;

            // ReferenceStencil
            internalState.ReferenceStencil = ReferenceStencil.HasValue ? ReferenceStencil.Value : currentState.ReferenceStencil;

            // Finally apply the state
            device.DepthStencilState = internalState;
        }
Example #5
0
 internal EffectPass(Effect effect, EffectPass cloneSource)
 {
   this._effect = effect;
   this.Name = cloneSource.Name;
   this._blendState = cloneSource._blendState;
   this._depthStencilState = cloneSource._depthStencilState;
   this._rasterizerState = cloneSource._rasterizerState;
   this.Annotations = cloneSource.Annotations;
   this._vertexShader = cloneSource._vertexShader;
   this._pixelShader = cloneSource._pixelShader;
 }
Example #6
0
 internal EffectPass(Effect effect, string name, Shader vertexShader, Shader pixelShader, BlendState blendState, DepthStencilState depthStencilState, RasterizerState rasterizerState, EffectAnnotationCollection annotations)
 {
   this._effect = effect;
   this.Name = name;
   this._vertexShader = vertexShader;
   this._pixelShader = pixelShader;
   this._blendState = blendState;
   this._depthStencilState = depthStencilState;
   this._rasterizerState = rasterizerState;
   this.Annotations = annotations;
   this.Initialize();
 }
Example #7
0
		/// <summary>
		/// Initializes a new instance of the StateFactory
		/// </summary>
		/// <param name="device"></param>
		/// <param name="ubershader"></param>
		private StateFactory ( Ubershader ubershader, Type enumType, Primitive primitive, VertexInputElement[] vertexInputElements, BlendState blendState, RasterizerState rasterizerState, DepthStencilState depthStencilState )
		 : base(ubershader.GraphicsDevice)
		{
			this.ubershader		= ubershader;

			Enumerate( enumType, ubershader, (ps,i) => { 
					ps.Primitive = primitive;
					ps.VertexInputElements	=	vertexInputElements; 
					ps.BlendState			=	blendState;
					ps.RasterizerState		=	rasterizerState;
					ps.DepthStencilState	=	depthStencilState;
				} );
		}
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            RemoveAndDispose(ref pixelShader);
            RemoveAndDispose(ref depthPixelShader);
            RemoveAndDispose(ref lambertShader);
            RemoveAndDispose(ref blinnPhongShader);
            RemoveAndDispose(ref phongShader);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);

            RemoveAndDispose(ref depthStencilState);

            // Get a reference to the Device1 instance and immediate context
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));
                // Layout from VertexShader input signature
                vertexLayout = ToDispose(new InputLayout(device,
                                                         vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                         new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                }));
            }

            // Compile and create the pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
                depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
                lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
                phongShader = ToDispose(new PixelShader(device, bytecode));

            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
                // Configure FrontFace depth/stencil operations
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment
                },
                // Configure BackFace depth/stencil operations
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement
                },
            }));

            // Tell the IA what the vertices will look like
            // in this case two 4-component 32bit floats
            // (32 bytes in total)
            context.InputAssembler.InputLayout = vertexLayout;

            // Set our constant buffer (to store worldViewProjection)
            context.VertexShader.SetConstantBuffer(0, perObjectBuffer);
            context.VertexShader.SetConstantBuffer(1, perFrameBuffer);
            context.VertexShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the vertex shader to run
            context.VertexShader.Set(vertexShader);

            // Set our pixel constant buffers
            context.PixelShader.SetConstantBuffer(1, perFrameBuffer);
            context.PixelShader.SetConstantBuffer(2, perMaterialBuffer);

            // Set the pixel shader to run
            context.PixelShader.Set(blinnPhongShader);

            // Set our depth stencil state
            context.OutputMerger.DepthStencilState = depthStencilState;

            // Back-face culling
            context.Rasterizer.State = ToDispose(new RasterizerState(device, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
            }));
        }
Example #9
0
        public void Shutdown()
        {
            // Before shutting down set to windowed mode or when you release the swap chain it will throw an exception.
            if (SwapChain != null)
            {
                SwapChain.SetFullscreenState(false, null);
            }

            if (AlphaEnableBlendingState != null)
            {
                AlphaEnableBlendingState.Dispose();
                AlphaEnableBlendingState = null;
            }

            if (AlphaDisableBlendingState != null)
            {
                AlphaDisableBlendingState.Dispose();
                AlphaDisableBlendingState = null;
            }

            if (DepthDisabledStencilState != null)
            {
                DepthDisabledStencilState.Dispose();
                DepthDisabledStencilState = null;
            }

            if (RasterState != null)
            {
                RasterState.Dispose();
                RasterState = null;
            }

            if (DepthStencilView != null)
            {
                DepthStencilView.Dispose();
                DepthStencilView = null;
            }

            if (DepthStencilState != null)
            {
                DepthStencilState.Dispose();
                DepthStencilState = null;
            }

            if (DepthStencilBuffer != null)
            {
                DepthStencilBuffer.Dispose();
                DepthStencilBuffer = null;
            }

            if (RenderTargetView != null)
            {
                RenderTargetView.Dispose();
                RenderTargetView = null;
            }

            if (Device != null)
            {
                Device.Dispose();
                Device = null;
            }

            if (SwapChain != null)
            {
                SwapChain.Dispose();
                SwapChain = null;
            }
        }
Example #10
0
        private void InitializeGraphics()
        {
            // Creating device (we accept dx10 cards or greater)
            FeatureLevel[] levels = {
                                        FeatureLevel.Level_11_0,
                                        FeatureLevel.Level_10_1,
                                        FeatureLevel.Level_10_0
                                    };

            // Defining our swap chain
            SwapChainDescription desc = new SwapChainDescription();
            desc.BufferCount = 1;
            desc.Usage = Usage.RenderTargetOutput;
            desc.ModeDescription = new ModeDescription(0, 0, new Rational(0, 0), Format.R8G8B8A8_UNorm);
            desc.SampleDescription = new SampleDescription(1, 0);
            desc.OutputHandle = form.Handle;
            desc.IsWindowed = true;
            desc.SwapEffect = SwapEffect.Discard;

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

            Format depthFormat = Format.D24_UNorm_S8_UInt;
            Texture2DDescription depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = depthFormat,
                Height = form.Height,
                Width = form.Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            depthBuffer = new Texture2D(device11, depthBufferDesc);

            DepthStencilViewDescription dsViewDesc = new DepthStencilViewDescription
            {
                Format = depthFormat,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0,
            };

            depthView = new DepthStencilView(device11, depthBuffer, dsViewDesc);

            DepthStencilStateDescription dsStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,

                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },

            };

            depthState = DepthStencilState.FromDescription(device11, dsStateDesc);

            // Getting back buffer
            backBuffer = Resource.FromSwapChain<Texture2D>(swapChain, 0);

            // Defining render view
            renderTargetView = new RenderTargetView(device11, backBuffer);
            device11.ImmediateContext.OutputMerger.DepthStencilState = depthState;
            device11.ImmediateContext.OutputMerger.SetTargets(depthView, renderTargetView);

            // Setup the raster description which will determine how and what polygons will be drawn.
            RasterizerStateDescription rasterDesc = new RasterizerStateDescription(){
                IsAntialiasedLineEnabled = false,
                CullMode = CullMode.None,
                DepthBias = 0,
                DepthBiasClamp = 0.0f,
                IsDepthClipEnabled = true,
                FillMode = FillMode.Solid,
                IsFrontCounterclockwise = false,
                IsMultisampleEnabled = false,
                IsScissorEnabled = false,
                SlopeScaledDepthBias = 0.0f,
            };

            // Create the rasterizer state from the description we just filled out.
            rasterState = RasterizerState.FromDescription(device11, rasterDesc);

            // Now set the rasterizer state.
            device11.ImmediateContext.Rasterizer.State = rasterState;
            device11.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
        }
Example #11
0
        void InitializeGraphicsDevice()
        {
            SpriteBatch     = new SpriteBatch(graphicsDevice);
            defaultEffect   = new BasicEffect(graphicsDevice);
            AlphaTestEffect = new AlphaTestEffect(graphicsDevice);

            PrimitiveEffect = new BasicEffect(graphicsDevice)
            {
                TextureEnabled     = false,
                VertexColorEnabled = true
            };

            depthEnableStencilState = new DepthStencilState
            {
                DepthBufferEnable      = true,
                DepthBufferWriteEnable = true,
                TwoSidedStencilMode    = true
            };

            depthDisableStencilState = new DepthStencilState
            {
                DepthBufferEnable = false
            };

            #if !WINDOWS_PHONE && !XBOX && !WINDOWS && !NETFX_CORE
            List <string> extensions = CCUtils.GetGLExtensions();
            foreach (string s in extensions)
            {
                switch (s)
                {
                case "GL_OES_depth24":
                    platformDepthFormat = CCDepthFormat.Depth24;
                    break;

                case "GL_IMG_texture_npot":
                    allowNonPower2Textures = true;
                    break;

                case "GL_NV_depth_nonlinear":                       // nVidia Depth 16 non-linear
                    platformDepthFormat = CCDepthFormat.Depth16;
                    break;

                case "GL_NV_texture_npot_2D_mipmap":                // nVidia - nPot textures and mipmaps
                    allowNonPower2Textures = true;
                    break;
                }
            }
            #endif

            projectionMatrix = Matrix.Identity;
            viewMatrix       = Matrix.Identity;
            worldMatrix      = Matrix.Identity;
            matrix           = Matrix.Identity;

            worldMatrixChanged = viewMatrixChanged = projectionMatrixChanged = true;

            // Need to change DrawPrim to no longer be static !!!
            CCDrawingPrimitives.Initialize(graphicsDevice, this);

            graphicsDevice.Disposing         += GraphicsDeviceDisposing;
            graphicsDevice.DeviceLost        += GraphicsDeviceDeviceLost;
            graphicsDevice.DeviceReset       += GraphicsDeviceDeviceReset;
            graphicsDevice.DeviceResetting   += GraphicsDeviceDeviceResetting;
            graphicsDevice.ResourceCreated   += GraphicsDeviceResourceCreated;
            graphicsDevice.ResourceDestroyed += GraphicsDeviceResourceDestroyed;
        }
        public MenuEffect(Device device)
        {
            Device = device;
            ImmediateContext = Device.ImmediateContext;

            // Compile the shader...
            string compileErrors;
            var compiledShader = SlimDX.D3DCompiler.ShaderBytecode.CompileFromFile
            (
                "../../Effects/MenuEffect/MenuEffect.fx",
                null,
                "fx_5_0",
                SlimDX.D3DCompiler.ShaderFlags.None,
                SlimDX.D3DCompiler.EffectFlags.None,
                null,
                null,
                out compileErrors
            );

            if (compileErrors != null && compileErrors != "")
            {
                throw new EffectBuildException(compileErrors);
            }

            Effect = new Effect(Device, compiledShader);
            Technique = Effect.GetTechniqueByName("MenuTechnique");

            var vertexDesc = new[]
            {
                new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 8, 0, InputClassification.PerVertexData, 0)
            };

            CPO_BlendColor = Effect.GetVariableByName("gBlendColor").AsVector();
            SRV_DiffuseMap = Effect.GetVariableByName("gDiffuseMap").AsResource();

            InputLayout = new InputLayout(Device, Technique.GetPassByIndex(0).Description.Signature, vertexDesc);

            Util.ReleaseCom(ref compiledShader);

            DepthStencilStateDescription dssd = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    Comparison = Comparison.Always
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always,
                    DepthFailOperation = StencilOperation.Decrement
                }
            };
            DepthDisabledState = DepthStencilState.FromDescription(Device, dssd);
        }
Example #13
0
		public void BeginRender(RenderTargetView imposterTarget, DepthStencilView depthView, DepthStencilState depthState, Color4 background, Viewport viewport, RenderTargetBackupState state)
		{
			if (m_Disposed == true)
			{
				return;
			}

			SlimDX.Direct3D11.DeviceContext context = GameEnvironment.Device.ImmediateContext;

			state.RenderTargets = context.OutputMerger.GetRenderTargets(1);
			state.Viewports = context.Rasterizer.GetViewports();

//			GameEnvironment.Device.OutputMerger.SetTargets(GameEnvironment.DepthView, GameEnvironment.RenderView);
//			GameEnvironment.Device.ClearDepthStencilView(GameEnvironment.DepthView, DepthStencilClearFlags.Depth, 1.0f, 0);
//			GameEnvironment.Device.OutputMerger.DepthStencilState = GameEnvironment.DepthState;


			context.OutputMerger.SetTargets(depthView, imposterTarget);
			context.Rasterizer.SetViewports(viewport);
			context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
			context.ClearRenderTargetView(imposterTarget, background);
			context.OutputMerger.DepthStencilState = depthState;
		}
Example #14
0
        public static void Initialize(Device device)
        {
            {
                var blendStateDescription = new BlendStateDescription();
                blendStateDescription.RenderTargets[0].BlendEnable           = false;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                blendStateDescription.RenderTargets[1].BlendEnable           = false;
                blendStateDescription.RenderTargets[1].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[2].BlendEnable           = false;
                blendStateDescription.RenderTargets[2].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[3].BlendEnable           = false;
                blendStateDescription.RenderTargets[3].RenderTargetWriteMask = ColorWriteMaskFlags.None;

                m_BlendStates[(int)BlendType.None] = BlendState.FromDescription(device, blendStateDescription);

                blendStateDescription.RenderTargets[0].BlendEnable           = true;
                blendStateDescription.RenderTargets[0].BlendOperation        = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].DestinationBlend      = BlendOption.One;
                blendStateDescription.RenderTargets[0].DestinationBlendAlpha = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlend           = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                m_BlendStates[(int)BlendType.Additive] = BlendState.FromDescription(device, blendStateDescription);
            }

            {
                var depthStencilStateDescription = new DepthStencilStateDescription();
                depthStencilStateDescription.DepthComparison  = Comparison.Always;
                depthStencilStateDescription.DepthWriteMask   = DepthWriteMask.Zero;
                depthStencilStateDescription.IsDepthEnabled   = false;
                depthStencilStateDescription.IsStencilEnabled = false;
                depthStencilStateDescription.DepthWriteMask   = DepthWriteMask.Zero;

                m_DepthStencilStates[(int)DepthConfigurationType.NoDepth] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthComparison = Comparison.LessEqual;
                depthStencilStateDescription.DepthWriteMask  = DepthWriteMask.All;
                depthStencilStateDescription.IsDepthEnabled  = true;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthWriteCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);
            }

            {
                var rasterizerStateDescription = new RasterizerStateDescription();
                rasterizerStateDescription.DepthBias                  = 0;
                rasterizerStateDescription.DepthBiasClamp             = 0;
                rasterizerStateDescription.FillMode                   = FillMode.Solid;
                rasterizerStateDescription.IsAntialiasedLineEnabled   = false;
                rasterizerStateDescription.IsDepthClipEnabled         = true;
                rasterizerStateDescription.IsMultisampleEnabled       = false;
                rasterizerStateDescription.IsScissorEnabled           = false;
                rasterizerStateDescription.SlopeScaledDepthBias       = 0;
                rasterizerStateDescription.CullMode                   = CullMode.None;
                m_RasterizerStates[(int)RasterizerStateType.CullNone] = RasterizerState.FromDescription(device, rasterizerStateDescription);

                rasterizerStateDescription.CullMode = CullMode.Front;
                m_RasterizerStates[(int)RasterizerStateType.CullFront] = RasterizerState.FromDescription(device, rasterizerStateDescription);

                rasterizerStateDescription.CullMode = CullMode.Back;
                m_RasterizerStates[(int)RasterizerStateType.CullBack] = RasterizerState.FromDescription(device, rasterizerStateDescription);
            }
        }
Example #15
0
		public void LoadResources()
		{
			if (m_Disposed == true)
			{
				m_BackBuffer = new Texture2D(GameEnvironment.Device, new Texture2DDescription()
				{
					Width = (int)Width,
					Height = (int)Height,
					Format = Format.R8G8B8A8_UNorm,
					ArraySize = 1,
					BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
					CpuAccessFlags = CpuAccessFlags.None,
					MipLevels = 1,
					OptionFlags = ResourceOptionFlags.None,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Default
				});

				m_RenderView = new RenderTargetView(GameEnvironment.Device, m_BackBuffer);
				m_TextureView = new ShaderResourceView(GameEnvironment.Device, m_BackBuffer);

				#region Create Depth Buffer

				m_DepthBuffer = new Texture2D(GameEnvironment.Device, new Texture2DDescription()
				{
					Width = Width,
					Height = Height,
					MipLevels = 1,
					ArraySize = 1,
					Format = Format.D32_Float,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Default,
					BindFlags = BindFlags.DepthStencil,
					CpuAccessFlags = CpuAccessFlags.None,
					OptionFlags = ResourceOptionFlags.None
				});

				m_DepthView = new DepthStencilView(GameEnvironment.Device, m_DepthBuffer, new DepthStencilViewDescription()
				{
					Format = Format.D32_Float,
					Dimension = DepthStencilViewDimension.Texture2D,
					MipSlice = 0
				});

				m_DepthState = DepthStencilState.FromDescription(GameEnvironment.Device, new DepthStencilStateDescription()
				{
					IsDepthEnabled = true,
					DepthWriteMask = DepthWriteMask.All,
					DepthComparison = Comparison.LessEqual,
					IsStencilEnabled = false,
					StencilReadMask = 0xff,
					StencilWriteMask = 0xff,

					BackFace = new DepthStencilOperationDescription()
					{
						Comparison = Comparison.Always,
						DepthFailOperation = StencilOperation.Decrement,
						FailOperation = StencilOperation.Keep,
						PassOperation = StencilOperation.Keep
					},

					FrontFace = new DepthStencilOperationDescription()
					{
						Comparison = Comparison.Always,
						DepthFailOperation = StencilOperation.Increment,
						FailOperation = StencilOperation.Keep,
						PassOperation = StencilOperation.Keep
					}
				});

				#endregion

				m_Disposed = false; 
			}
		}
Example #16
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_isDisposed)
            {
                if (disposing)
                {
                    // Dispose loaded game components
                    for (int i = 0; i < _components.Count; i++)
                    {
                        var disposable = _components[i] as IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                    _components = null;

                    if (Content != null)
                    {
                        Content.Dispose();
                        Content = null;
                    }

                    if (_graphicsDeviceManager != null)
                    {
                        (_graphicsDeviceManager as GraphicsDeviceManager).Dispose();
                        _graphicsDeviceManager = null;
                    }

                    if (Platform != null)
                    {
                        Platform.Activated   -= OnActivated;
                        Platform.Deactivated -= OnDeactivated;
                        _services.RemoveService(typeof(GamePlatform));
#if WINDOWS_STOREAPP
                        Platform.ViewStateChanged -= Platform_ApplicationViewChanged;
#endif
                        Platform.Dispose();
                        Platform = null;
                    }

                    Effect.FlushCache();
                    ContentTypeReaderManager.ClearTypeCreators();

#if WINDOWS_PHONE
                    TouchPanel.ResetState();
#endif

#if WINDOWS_MEDIA_SESSION
                    Media.MediaManagerState.CheckShutdown();
#endif

#if DIRECTX
                    SoundEffect.Shutdown();

                    BlendState.ResetStates();
                    DepthStencilState.ResetStates();
                    RasterizerState.ResetStates();
                    SamplerState.ResetStates();
#endif
                }
#if ANDROID
                Activity = null;
#endif
                _isDisposed = true;
                _instance   = null;
            }
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="state">Depth stencil state state</param>
 internal EngineDepthStencilState(DepthStencilState state, int stencilRef)
 {
     this.state      = state;
     this.StencilRef = stencilRef;
 }
Example #18
0
 private void InitializeDepthStencil()
 {
     dss         = DepthStencilState.Default;
     dss_depth   = dss;
     dss_nodepth = DepthStencilState.None;
 }
Example #19
0
 public void SetStencil(DepthStencilState stencil, bool noflush = false)
 {
     if (!noflush)
         Flush(); }
 public override void Execute()
 {
     depthStencilState = DepthStencilState.FromDescription(Game.Context.Device, Description);
     Game.Context.Immediate.OutputMerger.DepthStencilState = depthStencilState;
 }
Example #21
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                {
                    return;
                }

                renderView.Dispose();
                depthView.Dispose();
                DisposeBuffers();

                if (Form.WindowState == FormWindowState.Minimized)
                {
                    return;
                }

                _width  = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

            _width     = 1024;
            _height    = 768;
            _nearPlane = 1.0f;

            ambient = new Color4(Color.Gray.ToArgb());

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 10 device.");
                return;
            }


            // shader.fx

            const ShaderFlags shaderFlags = ShaderFlags.None;
            //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);

            shadowGenPass  = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);
            debugDrawPass  = technique.GetPassByName("debug");

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes    = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags    = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            _rasterizerStateDesc = new RasterizerStateDescription()
            {
                CullMode             = CullingEnabled ? CullMode.Back : CullMode.None,
                FillMode             = FillMode.Solid,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
            };
            _device.Rasterizer.State = new RasterizerState(_device, _rasterizerStateDesc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

            shaderByteCode = LoadShader("grender.fx", shaderFlags);

            effect2            = new Effect(_device, shaderByteCode);
            technique          = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass  = technique.GetPassByIndex(0);
            gBufferOverlayPass = technique.GetPassByIndex(1);

            info         = new InfoText(_device);
            _meshFactory = new MeshFactory(this);
            MeshFactory  = _meshFactory;

            CreateBuffers();
            GraphicsLibraryManager.LibraryStarted();
        }
Example #22
0
        void Initialize()
        {
            // shader.fx

            ShaderFlags shaderFlags = ShaderFlags.None;
            //ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization;
            ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\shader.fx", "fx_4_0", shaderFlags, EffectFlags.None);

            effect = new Effect(_device, shaderByteCode);
            EffectTechnique technique = effect.GetTechniqueByIndex(0);

            shadowGenPass  = technique.GetPassByIndex(0);
            gBufferGenPass = technique.GetPassByIndex(1);

            BufferDescription sceneConstantsDesc = new BufferDescription()
            {
                SizeInBytes    = Marshal.SizeOf(typeof(ShaderSceneConstants)),
                Usage          = ResourceUsage.Dynamic,
                BindFlags      = BindFlags.ConstantBuffer,
                CpuAccessFlags = CpuAccessFlags.Write,
                OptionFlags    = ResourceOptionFlags.None
            };

            sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc);
            EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene");

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

            RasterizerStateDescription desc = new RasterizerStateDescription()
            {
                CullMode = CullMode.None,
                FillMode = FillMode.Solid,
                IsFrontCounterClockwise = true,
                DepthBias            = 0,
                DepthBiasClamp       = 0,
                SlopeScaledDepthBias = 0,
                IsDepthClipEnabled   = true,
            };

            _device.Rasterizer.State = new RasterizerState(_device, desc);

            DepthStencilStateDescription depthDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            depthStencilState = new DepthStencilState(_device, depthDesc);

            DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                IsStencilEnabled = false,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Less
            };

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

            shaderByteCode = ShaderBytecode.CompileFromFile(Application.StartupPath + "\\grender.fx", "fx_4_0", shaderFlags, EffectFlags.None);

            effect2           = new Effect(_device, shaderByteCode);
            technique         = effect2.GetTechniqueByIndex(0);
            gBufferRenderPass = technique.GetPassByIndex(0);

            Buffer quad = MeshFactory.CreateScreenQuad(_device);

            quadBinding = new VertexBufferBinding(quad, 20, 0);
            Matrix quadProjection = Matrix.OrthoLH(1, 1, 0.1f, 1.0f);

            effect2.GetVariableByName("ViewProjection").AsMatrix().SetMatrix(quadProjection);

            InputElement[] elements = new InputElement[]
            {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0),
            };
            quadBufferLayout = new InputLayout(_device, gBufferRenderPass.Description.Signature, elements);


            Info        = new InfoText(_device);
            meshFactory = new MeshFactory(this);

            OnInitialize();
            CreateBuffers();
            SetSceneConstants();
        }
Example #23
0
        /// <summary>
        /// Creates a new instance of the SpriteRenderer
        /// </summary>
        /// <param name="device">The device to use</param>
        /// <param name="maxSpriteInstances">The maximum sprite instances that can be cached before a flush happens</param>
        public SpriteRenderer(Device device, int maxSpriteInstances = 10000)
        {
            /* Initialize our arrays to hold our sprite data */
            m_spriteRenderData = new SpriteRenderData[maxSpriteInstances];
            m_spriteDrawData = new SpriteDrawData[maxSpriteInstances];

            /* Initialize all the items in the array */
            for (int i = 0; i < maxSpriteInstances; i++)
            {
                m_spriteRenderData[i] = new SpriteRenderData();
            }

            m_maxSpriteInstances = maxSpriteInstances;
            m_device = device;

            /* Create our default blend states using our helper */
            m_blendStates = SpriteRendererBlendStateHelper.InitializeDefaultBlendStates(m_device);

            /* Create our vertex shader */
            m_vertexShaderInstanced10 = new VertexShader10(device,
                                                           SHADER_RESOURCE_NAME, Assembly.GetExecutingAssembly(),
                                                           "SpriteInstancedVS", 
                                                           ShaderVersion.Vs_4_0);

            /* Create our pixel shader */
            m_pixelShader10 = new PixelShader10(device,
                                                SHADER_RESOURCE_NAME, Assembly.GetExecutingAssembly(),
                                                "SpritePS", 
                                                ShaderVersion.Ps_4_0,ShaderFlags.Debug);
            
            /* Create a new sprite quad that holds our GPU buffers */
            m_spriteQuad = new SpriteQuad(device, maxSpriteInstances);

            m_spriteQuadShaderBinding = new GeometryInputShaderBinding(m_spriteQuad, 
                                                                       m_vertexShaderInstanced10, 
                                                                       m_pixelShader10);

            var rastDesc = new RasterizerStateDescription();
            rastDesc.IsAntialiasedLineEnabled = false;
            rastDesc.CullMode = CullMode.None;
            rastDesc.DepthBias = 0;
            rastDesc.DepthBiasClamp = 1.0f;
            rastDesc.IsDepthClipEnabled = false;
            rastDesc.FillMode = FillMode.Solid;
            rastDesc.IsFrontCounterclockwise = false;
            rastDesc.IsMultisampleEnabled = false;
            rastDesc.IsScissorEnabled = false;
            rastDesc.SlopeScaledDepthBias = 0;
            m_rasterizerState = RasterizerState.FromDescription(m_device, rastDesc);
            
            var dsDesc = new DepthStencilStateDescription();
            dsDesc.IsDepthEnabled = false;
            dsDesc.DepthWriteMask = DepthWriteMask.All;
            dsDesc.DepthComparison = Comparison.Less;
            dsDesc.IsStencilEnabled = false;
            dsDesc.StencilReadMask = 0xff;
            dsDesc.StencilWriteMask = 0xff;
            dsDesc.FrontFace = new DepthStencilOperationDescription{ DepthFailOperation = StencilOperation.Keep, FailOperation = StencilOperation.Replace, Comparison = Comparison.Always };
            dsDesc.BackFace = dsDesc.FrontFace;
            m_dsState = DepthStencilState.FromDescription(m_device, dsDesc);

            var sampDesc = new SamplerDescription();
            sampDesc.AddressU = TextureAddressMode.Wrap;
            sampDesc.AddressV = TextureAddressMode.Wrap;
            sampDesc.AddressW = TextureAddressMode.Wrap;
            sampDesc.BorderColor = new Color4(0, 0, 0, 0).InternalColor4;
            sampDesc.ComparisonFunction = Comparison.Never;
            sampDesc.Filter = Filter.MinMagMipLinear;
            sampDesc.MaximumAnisotropy = 1;
            sampDesc.MaximumLod = float.MaxValue;
            sampDesc.MinimumLod = 0;
            sampDesc.MipLodBias = 0;
            m_linearSamplerState = SamplerState.FromDescription(m_device, sampDesc);

            sampDesc.Filter = Filter.MinMagMipPoint;
            m_pointSamplerState = SamplerState.FromDescription(m_device, sampDesc);
        }
Example #24
0
 public virtual void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect)
 {
     this.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, Matrix.Identity);
 }
Example #25
0
        public HoverForm(Maze maze)
            : base("HoverRenderer")
        {
            this.ClientSize = new System.Drawing.Size(640, 480);

            var description = new SwapChainDescription()
            {
                BufferCount = 2,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = this.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
            using (var resource = Resource.FromSwapChain<Texture2D>(swapChain, 0))
            {
                renderTarget = new RenderTargetView(device, resource);
            }

            // Create the depth buffer
            var depthBufferDescription = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.D32_Float,
                Height = this.ClientSize.Height,
                Width = this.ClientSize.Width,
                MipLevels = 1,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };
            using (var depthBuffer = new Texture2D(device, depthBufferDescription))
            {
                depthStencilView = new DepthStencilView(device, depthBuffer);
                depthStencilState = DepthStencilState.FromDescription(device, new DepthStencilStateDescription {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.LessEqual
                });
            }

            // Setup wireframe mode
            rasteriserState = RasterizerState.FromDescription(device, new RasterizerStateDescription
            {
                CullMode = SlimDX.Direct3D11.CullMode.None,
                FillMode = SlimDX.Direct3D11.FillMode.Wireframe
            });

            // setting a viewport is required if you want to actually see anything
            context = device.ImmediateContext;
            var viewport = new Viewport(0.0f, 0.0f, this.ClientSize.Width, this.ClientSize.Height);
            context.OutputMerger.SetTargets(depthStencilView, renderTarget);
            context.OutputMerger.DepthStencilState = depthStencilState;
            context.Rasterizer.State = rasteriserState;
            context.Rasterizer.SetViewports(viewport);

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

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

            // create test vertex data, making sure to rewind the stream afterward
            vertices = CreateTriangleListFromMaze(maze);
            camera.Position = FindHumanStartPosition(maze);

            // create the vertex layout and buffer
            var elements = new[] {
                new InputElement("POSITION", 0, Format.R32G32B32_Float, 0),
                new InputElement("COLOR", 0, Format.R32G32B32_Float, 0)
            };
            layout = new InputLayout(device, inputSignature, elements);
            vertexBuffer = new Buffer(device, vertices, (int)vertices.Length, 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, 24, 0));

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

            // crate the constant buffer
            constantBuffer = new Buffer(device, new BufferDescription
            {
                Usage = ResourceUsage.Default,
                SizeInBytes = Marshal.SizeOf(typeof(ConstantBuffer)),
                BindFlags = BindFlags.ConstantBuffer
            });

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

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

            // handle form size changes
            this.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);
            };

            this.KeyDown += new KeyEventHandler(HoverForm_KeyDown);
        }
Example #26
0
 public virtual void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix)
 {
     this.spriteSortMode    = sortMode;
     this.blendState        = blendState;
     this.samplerState      = samplerState;
     this.depthStencilState = depthStencilState;
     this.rasterizerState   = rasterizerState;
     this.customEffect      = effect;
     this.transformMatrix   = transformMatrix;
 }
Example #27
0
        public TeapotScene(TeapotRenderer teapotRenderer)
        {
            // Create a description of the display mode
            ModeDescription modeDescription = new ModeDescription()
            {
                Format = Format.R8G8B8A8_UNorm,
                RefreshRate = new Rational(60, 1),
                
                Width = 512,
                Height = 512
            };

            // Create a description of the multisampler
            SampleDescription sampleDescription = new SampleDescription()
            {
                Count = 1,
                Quality = 0
            };

            // Create a description of the swap chain
            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                ModeDescription = modeDescription,
                SampleDescription = sampleDescription,

                BufferCount = 1,
                SwapEffect = SwapEffect.Discard,
                Usage = Usage.RenderTargetOutput,

                IsWindowed = false
            };

            // Create a hardware accelarated rendering device
            renderingDevice = new Device(DriverType.Hardware, DeviceCreationFlags.Debug | DeviceCreationFlags.BgraSupport);

            // Create the shared texture
            Texture2DDescription colordesc = new Texture2DDescription();
            colordesc.BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource;
            colordesc.Format = Format.B8G8R8A8_UNorm;
            colordesc.Width = 512;
            colordesc.Height = 512;
            colordesc.MipLevels = 1;
            colordesc.SampleDescription = new SampleDescription(1, 0);
            colordesc.Usage = ResourceUsage.Default;
            colordesc.OptionFlags = ResourceOptionFlags.Shared;
            colordesc.CpuAccessFlags = CpuAccessFlags.None;
            colordesc.ArraySize = 1;

            SharedTexture = new Texture2D(renderingDevice, colordesc);

            // Create the render target view
            renderTargetView = new RenderTargetView(renderingDevice, SharedTexture);

            // Creat the depth/stencil buffer
            DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,
            };

            depthStencilState = DepthStencilState.FromDescription(renderingDevice, depthStencilStateDescription);

            Texture2DDescription depthStencilTextureDescription = new Texture2DDescription()
            {
                Width = 512,
                Height = 512,
                MipLevels = 1,
                ArraySize = 1,
                Format = Format.D32_Float,
                SampleDescription = sampleDescription,
                Usage = ResourceUsage.Default,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None
            };

            DepthStencilViewDescription depthStencilViewDescription = new DepthStencilViewDescription()
            {
                Format = depthStencilTextureDescription.Format,
                Dimension = depthStencilTextureDescription.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D,
                MipSlice = 0
            };

            using (Texture2D depthStencilTexture = new Texture2D(renderingDevice, depthStencilTextureDescription))
            {
                depthStencilView = new DepthStencilView(renderingDevice, depthStencilTexture, depthStencilViewDescription);
            }

            // Setup the default output targets
            renderingDevice.ImmediateContext.OutputMerger.SetTargets(depthStencilView, renderTargetView);

            // Setup the viewport
            Viewport viewPort = new Viewport()
            {
                X = 0,
                Y = 0,
                Width = 512,
                Height = 512,
                MinZ = 0,
                MaxZ = 1
            };

            renderingDevice.ImmediateContext.Rasterizer.SetViewports(viewPort);

            // Create the teappot
            teapotObject = new TeapotObject(teapotRenderer, renderingDevice);

            // Create the camera
            camera = new ThirdPersonCamera(teapotObject);
            
        }
Example #28
0
 protected abstract void PlatformSetDepthStencilState(DepthStencilState depthStencilState);
        private void CreateStates()
        {
            var blendStateDesc = new BlendStateDescription();
            blendStateDesc.BlendOperation = BlendOperation.Add;
            blendStateDesc.AlphaBlendOperation = BlendOperation.Add;
            blendStateDesc.SourceBlend = BlendOption.One;
            blendStateDesc.DestinationBlend = BlendOption.One;
            blendStateDesc.SourceAlphaBlend = BlendOption.One;
            blendStateDesc.DestinationAlphaBlend = BlendOption.Zero;
            blendStateDesc.IsAlphaToCoverageEnabled = false;
            blendStateDesc.SetBlendEnable(0, true);
            visualEffectsBlendState = BlendState.FromDescription(renderer.Device, blendStateDesc);
            blendStateDesc.DestinationBlend = BlendOption.Zero;
            blenderBlendState = BlendState.FromDescription(renderer.Device, blendStateDesc);

            var rasterizerStateDesc = new RasterizerStateDescription();
            rasterizerStateDesc.CullMode = CullMode.None;
            rasterizerStateDesc.FillMode = FillMode.Solid;
            rasterizerStateDesc.IsAntialiasedLineEnabled = false;
            rasterizerStateDesc.IsMultisampleEnabled = false;
            // TODO: probably use scissor test
            rasterizerStateDesc.IsScissorEnabled = false;
            rasterizerState = RasterizerState.FromDescription(renderer.Device, rasterizerStateDesc);

            var depthStencilStateDesc = new DepthStencilStateDescription();
            depthStencilStateDesc.IsDepthEnabled = false;
            depthStencilStateDesc.IsStencilEnabled = false;
            depthStencilState = DepthStencilState.FromDescription(renderer.Device, depthStencilStateDesc);
        }
Example #30
0
 public void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencil, RasterizerState rasterizer)
 {
     Server.SendCommand(new CommandSpriteBatchBegin(
                            this, sortMode, blendState, samplerState, depthStencil, rasterizer, null));
 }
Example #31
0
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref lightBuffer);
            RemoveAndDispose(ref RTV);
            RemoveAndDispose(ref SRV);
            RemoveAndDispose(ref rsCullBack);
            RemoveAndDispose(ref rsCullFront);
            RemoveAndDispose(ref rsWireframe);
            RemoveAndDispose(ref blendStateAdd);
            RemoveAndDispose(ref depthLessThan);
            RemoveAndDispose(ref depthGreaterThan);
            RemoveAndDispose(ref depthDisabled);
            RemoveAndDispose(ref perLightBuffer);

            RemoveAndDispose(ref psAmbientLight);
            RemoveAndDispose(ref psDirectionalLight);
            RemoveAndDispose(ref psPointLight);
            RemoveAndDispose(ref psSpotLight);
            RemoveAndDispose(ref psDebugLight);
            RemoveAndDispose(ref perLightBuffer);

            // Retrieve our SharpDX.Direct3D11.Device1 instance
            var device = this.DeviceManager.Direct3DDevice;

            int width, height;
            SampleDescription sampleDesc;

            // Retrieve DSV from GBuffer and extract width/height
            // then create a new read-only DSV
            using (var depthTexture = gbuffer.DSV.ResourceAs <Texture2D>())
            {
                width      = depthTexture.Description.Width;
                height     = depthTexture.Description.Height;
                sampleDesc = depthTexture.Description.SampleDescription;

                // Initialize read-only DSV
                var dsvDesc = gbuffer.DSV.Description;
                dsvDesc.Flags = DepthStencilViewFlags.ReadOnlyDepth | DepthStencilViewFlags.ReadOnlyStencil;
                DSVReadonly   = ToDispose(new DepthStencilView(device, depthTexture, dsvDesc));
            }
            // Check if GBuffer is multi-sampled
            bool isMSAA = sampleDesc.Count > 1;

            // Initialize the light render target
            var texDesc = new Texture2DDescription();

            texDesc.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;
            texDesc.ArraySize         = 1;
            texDesc.CpuAccessFlags    = CpuAccessFlags.None;
            texDesc.Usage             = ResourceUsage.Default;
            texDesc.Width             = width;
            texDesc.Height            = height;
            texDesc.MipLevels         = 1; // No mip levels
            texDesc.SampleDescription = sampleDesc;
            texDesc.Format            = Format.R8G8B8A8_UNorm;

            lightBuffer = ToDispose(new Texture2D(device, texDesc));

            // Render Target View description
            var rtvDesc = new RenderTargetViewDescription();

            rtvDesc.Format             = Format.R8G8B8A8_UNorm;
            rtvDesc.Dimension          = isMSAA ? RenderTargetViewDimension.Texture2DMultisampled : RenderTargetViewDimension.Texture2D;
            rtvDesc.Texture2D.MipSlice = 0;
            RTV = ToDispose(new RenderTargetView(device, lightBuffer, rtvDesc));

            // SRV description for render targets
            var srvDesc = new ShaderResourceViewDescription();

            srvDesc.Format                    = Format.R8G8B8A8_UNorm;
            srvDesc.Dimension                 = isMSAA ? SharpDX.Direct3D.ShaderResourceViewDimension.Texture2DMultisampled : SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D;
            srvDesc.Texture2D.MipLevels       = -1;
            srvDesc.Texture2D.MostDetailedMip = 0;
            SRV = ToDispose(new ShaderResourceView(device, lightBuffer, srvDesc));

            // Initialize additive blend state (assuming single render target)
            BlendStateDescription bsDesc = new BlendStateDescription();

            bsDesc.RenderTarget[0].IsBlendEnabled        = true;
            bsDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.One;
            bsDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            bsDesc.RenderTarget[0].SourceBlend           = BlendOption.One;
            bsDesc.RenderTarget[0].DestinationBlend      = BlendOption.One;
            bsDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            blendStateAdd = ToDispose(new BlendState(device, bsDesc));

            // Initialize rasterizer states
            RasterizerStateDescription rsDesc = new RasterizerStateDescription();

            rsDesc.FillMode = FillMode.Solid;
            rsDesc.CullMode = CullMode.Back;
            rsCullBack      = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsCullFront     = ToDispose(new RasterizerState(device, rsDesc));
            rsDesc.CullMode = CullMode.Front;
            rsDesc.FillMode = FillMode.Wireframe;
            rsWireframe     = ToDispose(new RasterizerState(device, rsDesc));

            // Initialize depth state
            var dsDesc = new DepthStencilStateDescription();

            dsDesc.IsStencilEnabled = false;
            dsDesc.IsDepthEnabled   = true;

            // Less-than depth comparison
            dsDesc.DepthComparison = Comparison.Less;
            depthLessThan          = ToDispose(new DepthStencilState(device, dsDesc));
            // Greater-than depth comparison
            dsDesc.DepthComparison = Comparison.Greater;
            depthGreaterThan       = ToDispose(new DepthStencilState(device, dsDesc));
            // Depth/stencil testing disabled
            dsDesc.IsDepthEnabled = false;
            depthDisabled         = ToDispose(new DepthStencilState(device, dsDesc));

            // Buffer to light parameters
            perLightBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <PerLight>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            if (isMSAA)
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\LightsMS.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
            else
            {
                // Compile and create the vertex shader
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "VSLight", "vs_5_0"))
                    vertexShader = ToDispose(new VertexShader(device, bytecode));
                // Compile pixel shaders
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSAmbientLight", "ps_5_0"))
                    psAmbientLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDirectionalLight", "ps_5_0"))
                    psDirectionalLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSPointLight", "ps_5_0"))
                    psPointLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSSpotLight", "ps_5_0"))
                    psSpotLight = ToDispose(new PixelShader(device, bytecode));
                using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\Lights.hlsl", "PSDebugLight", "ps_5_0"))
                    psDebugLight = ToDispose(new PixelShader(device, bytecode));
            }
        }
Example #32
0
        public bool Initialize(int screenWidth, int screenHeight, bool vSync, IntPtr hwnd, bool fullScreen, float screenDepth, float screenNear)
        {
            try {
                vSyncEnabled = vSync;

                Rational refreshRate = new Rational(0, 0);

                var factory       = new Factory1();
                var adapter       = factory.Adapters[0];
                var adapterOutput = adapter.Outputs[0];

                var modes = adapterOutput.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                for (int i = 0; i < modes.Length; i++)
                {
                    if (modes[i].Width == screenWidth)
                    {
                        if (modes[i].Height == screenHeight)
                        {
                            refreshRate = modes[i].RefreshRate;
                        }
                    }
                }

                VideoCardMemory      = adapter.Description.DedicatedVideoMemory / 1024 / 1024;
                VideoCardDescription = adapter.Description.Description;

                adapterOutput.Dispose();
                adapter.Dispose();
                factory.Dispose();

                var swapChainDescription = new SwapChainDescription {
                    BufferCount     = 1,
                    ModeDescription =
                    {
                        Width            = screenWidth,
                        Height           = screenHeight,
                        Format           = Format.R8G8B8A8_UNorm,
                        RefreshRate      = vSyncEnabled ? refreshRate : new Rational(0, 0),
                        ScanlineOrdering = DisplayModeScanlineOrder.Unspecified,
                        Scaling          = DisplayModeScaling.Unspecified
                    },
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = hwnd,
                    SampleDescription = { Count = 1, Quality = 0 },
                    IsWindowed        = !fullScreen,
                    SwapEffect        = SwapEffect.Discard,
                    Flags             = SwapChainFlags.None
                };

                var featureLevel = FeatureLevel.Level_11_0;

                Device device;
                Device.CreateWithSwapChain(
                    DriverType.Hardware,
                    DeviceCreationFlags.Debug,
                    new[] { featureLevel },
                    swapChainDescription,
                    out device,
                    out swapChain
                    );
                Device        = device;
                DeviceContext = device.ImmediateContext;

                using (var backBuffer = swapChain.GetBackBuffer <Texture2D>(0)) {
                    renderTargetView = new RenderTargetView(device, backBuffer);
                }

                var depthBufferDescription = new Texture2DDescription {
                    Width             = screenWidth,
                    Height            = screenHeight,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                depthStencilBuffer = new Texture2D(device, depthBufferDescription);

                var depthStencilStateDescription = new DepthStencilStateDescription {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    FrontFace        =
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    BackFace =
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                depthStencilState = new DepthStencilState(device, depthStencilStateDescription);

                var depthStencilViewDescription = new DepthStencilViewDescription {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D =
                    {
                        MipSlice = 0
                    }
                };

                depthStencilView = new DepthStencilView(device, depthStencilBuffer, depthStencilViewDescription);

                DeviceContext.OutputMerger.SetRenderTargets(depthStencilView, renderTargetView);

                var rasterizerStateDescription = new RasterizerStateDescription {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = 0.0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = 0.0f
                };

                rasterizerState = new RasterizerState(device, rasterizerStateDescription);

                DeviceContext.Rasterizer.State = rasterizerState;

                var viewport = new Viewport {
                    Width    = screenWidth,
                    Height   = screenHeight,
                    MinDepth = 0.0f,
                    MaxDepth = 1.0f,
                    X        = 0,
                    Y        = 0
                };

                DeviceContext.Rasterizer.SetViewport(viewport);

                var fieldOfView  = MathUtil.Pi / 4.0f;
                var screenAspect = (float)screenWidth / screenHeight;
                Projection = Matrix.PerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
                World      = Matrix.Identity;
                Orthogonal = Matrix.OrthoLH(screenWidth, screenHeight, screenNear, screenDepth);
            } catch { return(false); }
            return(true);
        }
        public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled;
                var factory  = new Factory1();
                var adapter  = factory.GetAdapter1(0);
                var monitor  = adapter.GetOutput(0);
                var modes    = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }
                var adapterDescription = adapter.Description;
                VideoCardMemory      = adapterDescription.DedicatedVideoMemory >> 10 >> 10;
                VideoCardDescription = string.Format("VideoCard: {0}", adapterDescription.Description.Trim('\0'));
                monitor.Dispose();
                adapter.Dispose();
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                var swapChainDesc = new SwapChainDescription()
                {
                    BufferCount     = 1,
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm)
                    {
                        Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                    },
                    Usage             = Usage.RenderTargetOutput,
                    OutputHandle      = windowHandle,
                    SampleDescription = new SampleDescription(1, 0),
                    IsWindowed        = !DSystemConfiguration.FullScreen,
                    Flags             = SwapChainFlags.None,
                    SwapEffect        = SwapEffect.Discard
                };
                SharpDX.Direct3D11.Device device;
                SwapChain swapChain;
                SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);
                Device        = device;
                SwapChain     = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);
                RenderTargetView = new RenderTargetView(device, backBuffer);
                backBuffer.Dispose();
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    FrontFace        = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = .0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = .0f
                };
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                DeviceContext.Rasterizer.State = RasterState;
                ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f);
                DeviceContext.Rasterizer.SetViewport(ViewPort);
                #endregion

                #region Initialize matrices
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);
                WorldMatrix      = Matrix.Identity;
                OrthoMatrix      = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = false,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    FrontFace        = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                var blendStateDesc = new BlendStateDescription();
                blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
                blendStateDesc.RenderTarget[0].SourceBlend           = BlendOption.SourceAlpha;
                blendStateDesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
                blendStateDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.One;
                blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
                blendStateDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
                blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                AlphaEnableBlendingState = new BlendState(device, blendStateDesc);
                blendStateDesc.RenderTarget[0].IsBlendEnabled = false;
                AlphaDisableBlendingState = new BlendState(device, blendStateDesc);
                #endregion

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #34
0
        public override void Load()
        {
            base.Load();

            skyboxEffect = this.EffectSystemOld.BuildEffect("Skybox")
                           .Using(new StateShaderPlugin()
            {
                RenderPassPlugin = this, UseDepthStencilState = true
            })
                           .Using(new BasicShaderPlugin(
                                      new ShaderMixinSource()
            {
                Mixins = new List <ShaderClassSource>()
                {
                    new ShaderClassSource("SkyBox")
                },
                Compositions = new Dictionary <string, ShaderSource>()
                {
                    { "color", SkyBoxColor }
                }
            })
            {
                RenderPassPlugin = this
            })
                           .InstantiatePermutation();

            if (OfflineCompilation)
            {
                return;
            }

            Parameters.AddSources(MainPlugin.ViewParameters);

            var zBackgroundValue = MainTargetPlugin.ClearDepth;
            // Generates a quad for post effect rendering (should be utility function)
            var vertices = new[]
            {
                -1.0f, 1.0f, zBackgroundValue, 1.0f,
                1.0f, 1.0f, zBackgroundValue, 1.0f,
                -1.0f, -1.0f, zBackgroundValue, 1.0f,
                1.0f, -1.0f, zBackgroundValue, 1.0f,
            };

            Parameters.RegisterParameter(EffectPlugin.DepthStencilStateKey);
            Parameters.Set(TexturingKeys.Sampler, GraphicsDevice.SamplerStates.LinearWrap);

            // Use the quad for this effectMesh
            var quadData = new Mesh();

            quadData.Draw = new MeshDraw
            {
                DrawCount     = 4,
                PrimitiveType = PrimitiveType.TriangleStrip,
                VertexBuffers = new[]
                {
                    new VertexBufferBinding(Buffer.Vertex.New(GraphicsDevice, vertices), new VertexDeclaration(VertexElement.Position <Vector4>()), 4)
                }
            };

            RenderPass.StartPass += (context) =>
            {
                // Setup the Viewport
                context.GraphicsDevice.SetViewport(MainTargetPlugin.Viewport);

                // Setup the depth stencil and main render target.
                context.GraphicsDevice.SetRenderTarget(MainTargetPlugin.DepthStencil, MainTargetPlugin.RenderTarget);
            };

            RenderPass.EndPass += (context) => context.GraphicsDevice.UnsetRenderTargets();

            var skyboxMesh = new EffectMesh(skyboxEffect, quadData).KeepAliveBy(this);

            // If the main target plugin is not clearing anything, we assume that this is the job of the skybox plugin
            if (!MainTargetPlugin.EnableClearTarget && !MainTargetPlugin.EnableClearDepth)
            {
                var description = new DepthStencilStateDescription().Default();
                description.DepthBufferFunction = CompareFunction.Always;
                var alwaysWrite = DepthStencilState.New(GraphicsDevice, description);
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, alwaysWrite);
            }
            else
            {
                skyboxMesh.Parameters.Set(EffectPlugin.DepthStencilStateKey, MainTargetPlugin.DepthStencilState);
            }

            skyboxMesh.Parameters.AddSources(this.Parameters);
            RenderSystem.GlobalMeshes.AddMesh(skyboxMesh);
        }
        protected override void CreateDeviceDependentResources()
        {
            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexShaderInstanced);
            RemoveAndDispose(ref geomShader);
            RemoveAndDispose(ref pixelShader);

            RemoveAndDispose(ref blendState);
            RemoveAndDispose(ref linearSampler);

            RemoveAndDispose(ref perComputeBuffer);
            RemoveAndDispose(ref perFrame);

            // Dispose of any loaded particle textures
            particleTextureSRVs.ForEach(srv => RemoveAndDispose(ref srv));
            particleTextureSRVs.Clear();

            // Dispose of any compute shaders
            computeShaders.Select(kv => kv.Value).ToList().ForEach(cs => RemoveAndDispose(ref cs));
            computeShaders.Clear();

            var device = this.DeviceManager.Direct3DDevice;

            #region Compile Vertex/Pixel/Geometry shaders

            // Compile and create the vertex shader
            using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMain", "vs_5_0"))
                using (var vsInstance = HLSLCompiler.CompileFromFile(@"Shaders\ParticleVS.hlsl", "VSMainInstance", "vs_5_0"))
                    // Compile and create the pixel shader
                    using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticlePS.hlsl", "PSMain", "ps_5_0"))
                        // Compile and create the geometry shader
                        using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\ParticleGS.hlsl", "PointToQuadGS", "gs_5_0"))
                        {
                            vertexShader          = ToDispose(new VertexShader(device, vsBytecode));
                            vertexShaderInstanced = ToDispose(new VertexShader(device, vsInstance));
                            pixelShader           = ToDispose(new PixelShader(device, psBytecode));
                            geomShader            = ToDispose(new GeometryShader(device, gsBytecode));
                        }
            #endregion

            #region Blend States
            var blendDesc = new BlendStateDescription()
            {
                IndependentBlendEnable = false,
                AlphaToCoverageEnable  = false,
            };
            // Additive blend state that darkens
            blendDesc.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled        = true,
                BlendOperation        = BlendOperation.Add,
                AlphaBlendOperation   = BlendOperation.Add,
                SourceBlend           = BlendOption.SourceAlpha,
                DestinationBlend      = BlendOption.InverseSourceAlpha,
                SourceAlphaBlend      = BlendOption.One,
                DestinationAlphaBlend = BlendOption.Zero,
                RenderTargetWriteMask = ColorWriteMaskFlags.All
            };
            blendState = ToDispose(new BlendState(device, blendDesc));

            // Additive blend state that lightens
            // (needs a dark background)
            blendDesc.RenderTarget[0].DestinationBlend = BlendOption.One;

            blendStateLight = ToDispose(new BlendState(device, blendDesc));
            #endregion

            // depth stencil state to disable Z-buffer
            disableDepthWrite = ToDispose(new DepthStencilState(device, new DepthStencilStateDescription {
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.Zero,
                IsDepthEnabled   = true,
                IsStencilEnabled = false
            }));

            // Create a linear sampler
            linearSampler = ToDispose(new SamplerState(device, new SamplerStateDescription
            {
                AddressU   = TextureAddressMode.Wrap,
                AddressV   = TextureAddressMode.Wrap,
                AddressW   = TextureAddressMode.Wrap,
                Filter     = Filter.MinMagMipLinear, // Bilinear
                MaximumLod = float.MaxValue,
                MinimumLod = 0,
            }));

            // Create the per compute shader constant buffer
            perComputeBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ParticleConstants>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));
            // Create the particle frame buffer
            perFrame = ToDispose(new Buffer(device, Utilities.SizeOf <ParticleFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            particleTextureSRVs.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, "Particle.png")));
            particleTextureSRVs.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, "Snowflake.png")));
            particleTextureSRVs.Add(ToDispose(TextureLoader.ShaderResourceViewFromFile(device, "Square.png")));
            activeParticleTextureIndex = 0;

            // Reinitialize particles if > 0
            if (this.Constants.MaxParticles > 0)
            {
                InitializeParticles(this.Constants.MaxParticles, this.Constants.MaxLifetime);
            }
        }
Example #36
0
        protected override void CreateDeviceDependentResources(DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            // Release all resources
            RemoveAndDispose(ref vertexShader);

            //RemoveAndDispose(ref depthPixelShader);
            //RemoveAndDispose(ref depthPixelShaderBytecode);
            //RemoveAndDispose(ref lambertShader);

            RemoveAndDispose(ref blinnPhongShader);

            RemoveAndDispose(ref envMapVSShader);
            RemoveAndDispose(ref envMapGSShader);
            RemoveAndDispose(ref envMapPSShader);

            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref perObjectBuffer);
            RemoveAndDispose(ref perFrameBuffer);
            RemoveAndDispose(ref perMaterialBuffer);
            RemoveAndDispose(ref perArmatureBuffer);

            RemoveAndDispose(ref depthStencilState);

            RemoveAndDispose(ref rasterizerState);

            // Get a reference to the Device1 instance and immediate context
            var device  = deviceManager.Direct3DDevice;
            var context = deviceManager.Direct3DContext;

            // Compile and create the vertex shader and input layout
            using (var vertexShaderBytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = ToDispose(new VertexShader(device, vertexShaderBytecode));
                // Layout from VertexShader input signature
                vertexLayout = ToDispose(new InputLayout(device,
                                                         vertexShaderBytecode.GetPart(ShaderBytecodePart.InputSignatureBlob),
                                                         new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                    // "SkinIndices"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "SkinWeights"
                    new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                }));
            }

            // Compile and create the pixel shader
            //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
            //    pixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the depth vertex and pixel shaders
            // This shader is for checking what the depth buffer would look like
            //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DepthPS.hlsl", "PSMain", "ps_5_0"))
            //    depthPixelShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\DiffusePS.hlsl", "PSMain", "ps_5_0"))
            //    lambertShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the blinn phong pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\BlinnPhongPS.hlsl", "PSMain", "ps_5_0"))
                blinnPhongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile and create the Lambert pixel shader
            //using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\PhongPS.hlsl", "PSMain", "ps_5_0"))
            //    phongShader = ToDispose(new PixelShader(device, bytecode));

            // Compile DualMap VS and GS shaders
            using (var vsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "VS_DualMap", "vs_5_0", null))
                using (var gsBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "GS_DualMap", "gs_5_0", null))
                    using (var psBytecode = HLSLCompiler.CompileFromFile(@"Shaders\DualParaboloidMap.hlsl", "PS_DualMap", "ps_5_0", null))
                    {
                        envMapVSShader = ToDispose(new VertexShader(device, vsBytecode));
                        envMapGSShader = ToDispose(new GeometryShader(device, gsBytecode));
                        envMapPSShader = ToDispose(new PixelShader(device, psBytecode));
                    }

            // IMPORTANT: A constant buffer's size must be a multiple of 16-bytes
            // use LayoutKind.Explicit and an explicit Size= to force this for structures
            // or alternatively add padding fields and use a LayoutKind.Sequential and Pack=1

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
                // Configure FrontFace depth/stencil operations
                FrontFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment
                },
                // Configure BackFace depth/stencil operations
                BackFace = new DepthStencilOperationDescription()
                {
                    Comparison         = Comparison.Always,
                    PassOperation      = StencilOperation.Keep,
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement
                },
            }));

            rasterizerState = ToDispose(new RasterizerState(this.DeviceManager.Direct3DDevice, new RasterizerStateDescription()
            {
                FillMode = FillMode.Solid,
                CullMode = CullMode.Back,
            }));

            // Initialize the ImmediateContext pipeline stages
            //InitializeContext(context, true);
        }
        public bool Initialize(DSystemConfiguration configuration, IntPtr windowHandle)
        {
            try
            {
                #region Environment Configuration
                // Store the vsync setting.
                VerticalSyncEnabled = DSystemConfiguration.VerticalSyncEnabled;

                // Create a DirectX graphics interface factory.
                var factory = new Factory1();

                // Use the factory to create an adapter for the primary graphics interface (video card).
                var adapter = factory.GetAdapter1(0);

                // Get the primary adapter output (monitor).
                var monitor = adapter.GetOutput(0);

                // Get modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
                var modes = monitor.GetDisplayModeList(Format.R8G8B8A8_UNorm, DisplayModeEnumerationFlags.Interlaced);

                // Now go through all the display modes and find the one that matches the screen width and height.
                // When a match is found store the the refresh rate for that monitor, if vertical sync is enabled.
                // Otherwise we use maximum refresh rate.
                var rational = new Rational(0, 1);
                if (VerticalSyncEnabled)
                {
                    foreach (var mode in modes)
                    {
                        if (mode.Width == configuration.Width && mode.Height == configuration.Height)
                        {
                            rational = new Rational(mode.RefreshRate.Numerator, mode.RefreshRate.Denominator);
                            break;
                        }
                    }
                }

                // Get the adapter (video card) description.
                var adapterDescription = adapter.Description;

                // Store the dedicated video card memory in megabytes.
                VideoCardMemory = adapterDescription.DedicatedVideoMemory >> 10 >> 10;

                // Convert the name of the video card to a character array and store it.
                VideoCardDescription = adapterDescription.Description.Trim('\0');

                // Release the adapter output.
                monitor.Dispose();
                // Release the adapter.
                adapter.Dispose();
                // Release the factory.
                factory.Dispose();
                #endregion

                #region Initialize swap chain and d3d device
                // Initialize the swap chain description.
                var swapChainDesc = new SwapChainDescription()
                {
                    // Set to a single back buffer.
                    BufferCount = 1,
                    // Set the width and height of the back buffer.
                    ModeDescription = new ModeDescription(configuration.Width, configuration.Height, rational, Format.R8G8B8A8_UNorm)
                    {
                        Scaling = DisplayModeScaling.Unspecified, ScanlineOrdering = DisplayModeScanlineOrder.Unspecified
                    },
                    // Set the usage of the back buffer.
                    Usage = Usage.RenderTargetOutput,
                    // Set the handle for the window to render to.
                    OutputHandle = windowHandle,
                    // Turn multisampling off.
                    SampleDescription = new SampleDescription(1, 0),
                    // Set to full screen or windowed mode.
                    IsWindowed = !DSystemConfiguration.FullScreen,
                    // Don't set the advanced flags.
                    Flags = SwapChainFlags.None,
                    // Discard the back buffer content after presenting.
                    SwapEffect = SwapEffect.Discard
                };

                // Create the swap chain, Direct3D device, and Direct3D device context.
                SharpDX.Direct3D11.Device device;
                SwapChain swapChain;
                SharpDX.Direct3D11.Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, swapChainDesc, out device, out swapChain);

                Device        = device;
                SwapChain     = swapChain;
                DeviceContext = device.ImmediateContext;
                #endregion

                #region Initialize buffers
                // Get the pointer to the back buffer.
                var backBuffer = Texture2D.FromSwapChain <Texture2D>(SwapChain, 0);

                // Create the render target view with the back buffer pointer.
                RenderTargetView = new RenderTargetView(device, backBuffer);

                // Release pointer to the back buffer as we no longer need it.
                backBuffer.Dispose();

                // Initialize and set up the description of the depth buffer.
                var depthBufferDesc = new Texture2DDescription()
                {
                    Width             = configuration.Width,
                    Height            = configuration.Height,
                    MipLevels         = 1,
                    ArraySize         = 1,
                    Format            = Format.D24_UNorm_S8_UInt,
                    SampleDescription = new SampleDescription(1, 0),
                    Usage             = ResourceUsage.Default,
                    BindFlags         = BindFlags.DepthStencil,
                    CpuAccessFlags    = CpuAccessFlags.None,
                    OptionFlags       = ResourceOptionFlags.None
                };

                // Create the texture for the depth buffer using the filled out description.
                DepthStencilBuffer = new Texture2D(device, depthBufferDesc);
                #endregion

                #region Initialize Depth Enabled Stencil
                // Initialize and set up the description of the stencil state.
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = true,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthStencilState = new DepthStencilState(Device, depthStencilDesc);
                #endregion

                #region Initialize Output Merger
                // Set the depth stencil state.
                DeviceContext.OutputMerger.SetDepthStencilState(DepthStencilState, 1);

                // Initialize and set up the depth stencil view.
                var depthStencilViewDesc = new DepthStencilViewDescription()
                {
                    Format    = Format.D24_UNorm_S8_UInt,
                    Dimension = DepthStencilViewDimension.Texture2D,
                    Texture2D = new DepthStencilViewDescription.Texture2DResource()
                    {
                        MipSlice = 0
                    }
                };

                // Create the depth stencil view.
                DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

                // Bind the render target view and depth stencil buffer to the output render pipeline.
                DeviceContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);
                #endregion

                #region Initialize Raster State
                // Setup the raster description which will determine how and what polygon will be drawn.
                var rasterDesc = new RasterizerStateDescription()
                {
                    IsAntialiasedLineEnabled = false,
                    CullMode                = CullMode.Back,
                    DepthBias               = 0,
                    DepthBiasClamp          = .0f,
                    IsDepthClipEnabled      = true,
                    FillMode                = FillMode.Solid,
                    IsFrontCounterClockwise = false,
                    IsMultisampleEnabled    = false,
                    IsScissorEnabled        = false,
                    SlopeScaledDepthBias    = .0f
                };

                // Create the rasterizer state from the description we just filled out.
                RasterState = new RasterizerState(Device, rasterDesc);
                #endregion

                #region Initialize Rasterizer
                // Now set the rasterizer state.
                DeviceContext.Rasterizer.State = RasterState;

                ViewPort = new ViewportF(0.0f, 0.0f, (float)configuration.Width, (float)configuration.Height, 0.0f, 1.0f);

                // Setup and create the viewport for rendering.
                DeviceContext.Rasterizer.SetViewport(ViewPort);
                #endregion

                #region Initialize matrices
                // Setup and create the projection matrix.
                ProjectionMatrix = Matrix.PerspectiveFovLH((float)(Math.PI / 4), ((float)configuration.Width / (float)configuration.Height), DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);

                // Initialize the world matrix to the identity matrix.
                WorldMatrix = Matrix.Identity;

                // Create an orthographic projection matrix for 2D rendering.
                OrthoMatrix = Matrix.OrthoLH(configuration.Width, configuration.Height, DSystemConfiguration.ScreenNear, DSystemConfiguration.ScreenDepth);
                #endregion

                #region Initialize Depth Disabled Stencil
                // Now create a second depth stencil state which turns off the Z buffer for 2D rendering. Added in Tutorial 11
                // The difference is that DepthEnable is set to false.
                // All other parameters are the same as the other depth stencil state.
                var depthDisabledStencilDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled   = false,
                    DepthWriteMask   = DepthWriteMask.All,
                    DepthComparison  = Comparison.Less,
                    IsStencilEnabled = true,
                    StencilReadMask  = 0xFF,
                    StencilWriteMask = 0xFF,
                    // Stencil operation if pixel front-facing.
                    FrontFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Increment,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    },
                    // Stencil operation if pixel is back-facing.
                    BackFace = new DepthStencilOperationDescription()
                    {
                        FailOperation      = StencilOperation.Keep,
                        DepthFailOperation = StencilOperation.Decrement,
                        PassOperation      = StencilOperation.Keep,
                        Comparison         = Comparison.Always
                    }
                };

                // Create the depth stencil state.
                DepthDisabledStencilState = new DepthStencilState(Device, depthDisabledStencilDesc);
                #endregion

                #region Initialize Blend States
                #endregion

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #38
0
        private static void Main()
        {
            RenderForm form = new RenderForm("OculusWrap SharpDX demo");

            IntPtr          sessionPtr;
            InputLayout     inputLayout          = null;
            Buffer          contantBuffer        = null;
            Buffer          vertexBuffer         = null;
            ShaderSignature shaderSignature      = null;
            PixelShader     pixelShader          = null;
            ShaderBytecode  pixelShaderByteCode  = null;
            VertexShader    vertexShader         = null;
            ShaderBytecode  vertexShaderByteCode = null;
            Texture2D       mirrorTextureD3D     = null;

            EyeTexture[]      eyeTextures                = null;
            DeviceContext     immediateContext           = null;
            DepthStencilState depthStencilState          = null;
            DepthStencilView  depthStencilView           = null;
            Texture2D         depthBuffer                = null;
            RenderTargetView  backBufferRenderTargetView = null;
            Texture2D         backBuffer = null;

            SharpDX.DXGI.SwapChain swapChain = null;
            Factory       factory            = null;
            MirrorTexture mirrorTexture      = null;
            Guid          textureInterfaceId = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");                                                            // Interface ID of the Direct3D Texture2D interface.

            Result result;

            OvrWrap OVR = OvrWrap.Create();

            // Define initialization parameters with debug flag.
            InitParams initializationParameters = new InitParams();

            initializationParameters.Flags = InitFlags.Debug | InitFlags.RequestVersion;
            initializationParameters.RequestedMinorVersion = 17;

            // Initialize the Oculus runtime.
            string errorReason = null;

            try
            {
                result = OVR.Initialize(initializationParameters);

                if (result < Result.Success)
                {
                    errorReason = result.ToString();
                }
            }
            catch (Exception ex)
            {
                errorReason = ex.Message;
            }

            if (errorReason != null)
            {
                MessageBox.Show("Failed to initialize the Oculus runtime library:\r\n" + errorReason, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Use the head mounted display.
            sessionPtr = IntPtr.Zero;
            var graphicsLuid = new GraphicsLuid();

            result = OVR.Create(ref sessionPtr, ref graphicsLuid);
            if (result < Result.Success)
            {
                MessageBox.Show("The HMD is not enabled: " + result.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var hmdDesc = OVR.GetHmdDesc(sessionPtr);


            try
            {
                // Create a set of layers to submit.
                eyeTextures = new EyeTexture[2];

                // Create DirectX drawing device.
                SharpDX.Direct3D11.Device device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.Debug);

                // Create DirectX Graphics Interface factory, used to create the swap chain.
                factory = new SharpDX.DXGI.Factory4();

                immediateContext = device.ImmediateContext;

                // Define the properties of the swap chain.
                SwapChainDescription swapChainDescription = new SwapChainDescription();
                swapChainDescription.BufferCount            = 1;
                swapChainDescription.IsWindowed             = true;
                swapChainDescription.OutputHandle           = form.Handle;
                swapChainDescription.SampleDescription      = new SampleDescription(1, 0);
                swapChainDescription.Usage                  = Usage.RenderTargetOutput | Usage.ShaderInput;
                swapChainDescription.SwapEffect             = SwapEffect.Sequential;
                swapChainDescription.Flags                  = SwapChainFlags.AllowModeSwitch;
                swapChainDescription.ModeDescription.Width  = form.Width;
                swapChainDescription.ModeDescription.Height = form.Height;
                swapChainDescription.ModeDescription.Format = Format.R8G8B8A8_UNorm;
                swapChainDescription.ModeDescription.RefreshRate.Numerator   = 0;
                swapChainDescription.ModeDescription.RefreshRate.Denominator = 1;

                // Create the swap chain.
                swapChain = new SwapChain(factory, device, swapChainDescription);

                // Retrieve the back buffer of the swap chain.
                backBuffer = swapChain.GetBackBuffer <Texture2D>(0);
                backBufferRenderTargetView = new RenderTargetView(device, backBuffer);

                // Create a depth buffer, using the same width and height as the back buffer.
                Texture2DDescription depthBufferDescription = new Texture2DDescription();
                depthBufferDescription.Format            = Format.D32_Float;
                depthBufferDescription.ArraySize         = 1;
                depthBufferDescription.MipLevels         = 1;
                depthBufferDescription.Width             = form.Width;
                depthBufferDescription.Height            = form.Height;
                depthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                depthBufferDescription.Usage             = ResourceUsage.Default;
                depthBufferDescription.BindFlags         = BindFlags.DepthStencil;
                depthBufferDescription.CpuAccessFlags    = CpuAccessFlags.None;
                depthBufferDescription.OptionFlags       = ResourceOptionFlags.None;

                // Define how the depth buffer will be used to filter out objects, based on their distance from the viewer.
                DepthStencilStateDescription depthStencilStateDescription = new DepthStencilStateDescription();
                depthStencilStateDescription.IsDepthEnabled  = true;
                depthStencilStateDescription.DepthComparison = Comparison.Less;
                depthStencilStateDescription.DepthWriteMask  = DepthWriteMask.Zero;

                // Create the depth buffer.
                depthBuffer       = new Texture2D(device, depthBufferDescription);
                depthStencilView  = new DepthStencilView(device, depthBuffer);
                depthStencilState = new DepthStencilState(device, depthStencilStateDescription);

                var viewport = new Viewport(0, 0, hmdDesc.Resolution.Width, hmdDesc.Resolution.Height, 0.0f, 1.0f);

                immediateContext.OutputMerger.SetDepthStencilState(depthStencilState);
                immediateContext.OutputMerger.SetRenderTargets(depthStencilView, backBufferRenderTargetView);
                immediateContext.Rasterizer.SetViewport(viewport);

                // Retrieve the DXGI device, in order to set the maximum frame latency.
                using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>())
                {
                    dxgiDevice.MaximumFrameLatency = 1;
                }

                var layerEyeFov = new LayerEyeFov();
                layerEyeFov.Header.Type  = LayerType.EyeFov;
                layerEyeFov.Header.Flags = LayerFlags.None;

                for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                {
                    EyeType eye        = (EyeType)eyeIndex;
                    var     eyeTexture = new EyeTexture();
                    eyeTextures[eyeIndex] = eyeTexture;

                    // Retrieve size and position of the texture for the current eye.
                    eyeTexture.FieldOfView           = hmdDesc.DefaultEyeFov[eyeIndex];
                    eyeTexture.TextureSize           = OVR.GetFovTextureSize(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex], 1.0f);
                    eyeTexture.RenderDescription     = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);
                    eyeTexture.HmdToEyeViewOffset    = eyeTexture.RenderDescription.HmdToEyePose.Position;
                    eyeTexture.ViewportSize.Position = new Vector2i(0, 0);
                    eyeTexture.ViewportSize.Size     = eyeTexture.TextureSize;
                    eyeTexture.Viewport = new Viewport(0, 0, eyeTexture.TextureSize.Width, eyeTexture.TextureSize.Height, 0.0f, 1.0f);

                    // Define a texture at the size recommended for the eye texture.
                    eyeTexture.Texture2DDescription                   = new Texture2DDescription();
                    eyeTexture.Texture2DDescription.Width             = eyeTexture.TextureSize.Width;
                    eyeTexture.Texture2DDescription.Height            = eyeTexture.TextureSize.Height;
                    eyeTexture.Texture2DDescription.ArraySize         = 1;
                    eyeTexture.Texture2DDescription.MipLevels         = 1;
                    eyeTexture.Texture2DDescription.Format            = Format.R8G8B8A8_UNorm;
                    eyeTexture.Texture2DDescription.SampleDescription = new SampleDescription(1, 0);
                    eyeTexture.Texture2DDescription.Usage             = ResourceUsage.Default;
                    eyeTexture.Texture2DDescription.CpuAccessFlags    = CpuAccessFlags.None;
                    eyeTexture.Texture2DDescription.BindFlags         = BindFlags.ShaderResource | BindFlags.RenderTarget;

                    // Convert the SharpDX texture description to the Oculus texture swap chain description.
                    TextureSwapChainDesc textureSwapChainDesc = SharpDXHelpers.CreateTextureSwapChainDescription(eyeTexture.Texture2DDescription);

                    // Create a texture swap chain, which will contain the textures to render to, for the current eye.
                    IntPtr textureSwapChainPtr;

                    result = OVR.CreateTextureSwapChainDX(sessionPtr, device.NativePointer, ref textureSwapChainDesc, out textureSwapChainPtr);
                    WriteErrorDetails(OVR, result, "Failed to create swap chain.");

                    eyeTexture.SwapTextureSet = new TextureSwapChain(OVR, sessionPtr, textureSwapChainPtr);


                    // Retrieve the number of buffers of the created swap chain.
                    int textureSwapChainBufferCount;
                    result = eyeTexture.SwapTextureSet.GetLength(out textureSwapChainBufferCount);
                    WriteErrorDetails(OVR, result, "Failed to retrieve the number of buffers of the created swap chain.");

                    // Create room for each DirectX texture in the SwapTextureSet.
                    eyeTexture.Textures          = new Texture2D[textureSwapChainBufferCount];
                    eyeTexture.RenderTargetViews = new RenderTargetView[textureSwapChainBufferCount];

                    // Create a texture 2D and a render target view, for each unmanaged texture contained in the SwapTextureSet.
                    for (int textureIndex = 0; textureIndex < textureSwapChainBufferCount; textureIndex++)
                    {
                        // Retrieve the Direct3D texture contained in the Oculus TextureSwapChainBuffer.
                        IntPtr swapChainTextureComPtr = IntPtr.Zero;
                        result = eyeTexture.SwapTextureSet.GetBufferDX(textureIndex, textureInterfaceId, out swapChainTextureComPtr);
                        WriteErrorDetails(OVR, result, "Failed to retrieve a texture from the created swap chain.");

                        // Create a managed Texture2D, based on the unmanaged texture pointer.
                        eyeTexture.Textures[textureIndex] = new Texture2D(swapChainTextureComPtr);

                        // Create a render target view for the current Texture2D.
                        eyeTexture.RenderTargetViews[textureIndex] = new RenderTargetView(device, eyeTexture.Textures[textureIndex]);
                    }

                    // Define the depth buffer, at the size recommended for the eye texture.
                    eyeTexture.DepthBufferDescription                   = new Texture2DDescription();
                    eyeTexture.DepthBufferDescription.Format            = Format.D32_Float;
                    eyeTexture.DepthBufferDescription.Width             = eyeTexture.TextureSize.Width;
                    eyeTexture.DepthBufferDescription.Height            = eyeTexture.TextureSize.Height;
                    eyeTexture.DepthBufferDescription.ArraySize         = 1;
                    eyeTexture.DepthBufferDescription.MipLevels         = 1;
                    eyeTexture.DepthBufferDescription.SampleDescription = new SampleDescription(1, 0);
                    eyeTexture.DepthBufferDescription.Usage             = ResourceUsage.Default;
                    eyeTexture.DepthBufferDescription.BindFlags         = BindFlags.DepthStencil;
                    eyeTexture.DepthBufferDescription.CpuAccessFlags    = CpuAccessFlags.None;
                    eyeTexture.DepthBufferDescription.OptionFlags       = ResourceOptionFlags.None;

                    // Create the depth buffer.
                    eyeTexture.DepthBuffer      = new Texture2D(device, eyeTexture.DepthBufferDescription);
                    eyeTexture.DepthStencilView = new DepthStencilView(device, eyeTexture.DepthBuffer);

                    // Specify the texture to show on the HMD.
                    if (eyeIndex == 0)
                    {
                        layerEyeFov.ColorTextureLeft      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportLeft.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportLeft.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovLeft = eyeTexture.FieldOfView;
                    }
                    else
                    {
                        layerEyeFov.ColorTextureRight      = eyeTexture.SwapTextureSet.TextureSwapChainPtr;
                        layerEyeFov.ViewportRight.Position = new Vector2i(0, 0);
                        layerEyeFov.ViewportRight.Size     = eyeTexture.TextureSize;
                        layerEyeFov.FovRight = eyeTexture.FieldOfView;
                    }
                }

                MirrorTextureDesc mirrorTextureDescription = new MirrorTextureDesc();
                mirrorTextureDescription.Format    = TextureFormat.R8G8B8A8_UNorm_SRgb;
                mirrorTextureDescription.Width     = form.Width;
                mirrorTextureDescription.Height    = form.Height;
                mirrorTextureDescription.MiscFlags = TextureMiscFlags.None;

                // Create the texture used to display the rendered result on the computer monitor.
                IntPtr mirrorTexturePtr;
                result = OVR.CreateMirrorTextureDX(sessionPtr, device.NativePointer, ref mirrorTextureDescription, out mirrorTexturePtr);
                WriteErrorDetails(OVR, result, "Failed to create mirror texture.");

                mirrorTexture = new MirrorTexture(OVR, sessionPtr, mirrorTexturePtr);


                // Retrieve the Direct3D texture contained in the Oculus MirrorTexture.
                IntPtr mirrorTextureComPtr = IntPtr.Zero;
                result = mirrorTexture.GetBufferDX(textureInterfaceId, out mirrorTextureComPtr);
                WriteErrorDetails(OVR, result, "Failed to retrieve the texture from the created mirror texture buffer.");

                // Create a managed Texture2D, based on the unmanaged texture pointer.
                mirrorTextureD3D = new Texture2D(mirrorTextureComPtr);

                #region Vertex and pixel shader
                // Create vertex shader.
                vertexShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "VertexShaderPositionColor", "vs_4_0");
                vertexShader         = new VertexShader(device, vertexShaderByteCode);

                // Create pixel shader.
                pixelShaderByteCode = ShaderBytecode.CompileFromFile("Shaders.fx", "PixelShaderPositionColor", "ps_4_0");
                pixelShader         = new PixelShader(device, pixelShaderByteCode);

                shaderSignature = ShaderSignature.GetInputSignature(vertexShaderByteCode);

                // Specify that each vertex consists of a single vertex position and color.
                InputElement[] inputElements = new InputElement[]
                {
                    new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                    new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                };

                // Define an input layout to be passed to the vertex shader.
                inputLayout = new InputLayout(device, shaderSignature, inputElements);

                // Create a vertex buffer, containing our 3D model.
                vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, m_vertices);

                // Create a constant buffer, to contain our WorldViewProjection matrix, that will be passed to the vertex shader.
                contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);

                // Setup the immediate context to use the shaders and model we defined.
                immediateContext.InputAssembler.InputLayout       = inputLayout;
                immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
                immediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBuffer, sizeof(float) * 4 * 2, 0));
                immediateContext.VertexShader.SetConstantBuffer(0, contantBuffer);
                immediateContext.VertexShader.Set(vertexShader);
                immediateContext.PixelShader.Set(pixelShader);
                #endregion

                DateTime startTime = DateTime.Now;
                Vector3  position  = new Vector3(0, 0, -1);

                #region Render loop
                RenderLoop.Run(form, () =>
                {
                    Vector3f[] hmdToEyeViewOffsets = { eyeTextures[0].HmdToEyeViewOffset, eyeTextures[1].HmdToEyeViewOffset };
                    double displayMidpoint         = OVR.GetPredictedDisplayTime(sessionPtr, 0);
                    TrackingState trackingState    = OVR.GetTrackingState(sessionPtr, displayMidpoint, true);
                    Posef[] eyePoses = new Posef[2];

                    // Calculate the position and orientation of each eye.
                    OVR.CalcEyePoses(trackingState.HeadPose.ThePose, hmdToEyeViewOffsets, ref eyePoses);

                    float timeSinceStart = (float)(DateTime.Now - startTime).TotalSeconds;

                    for (int eyeIndex = 0; eyeIndex < 2; eyeIndex++)
                    {
                        EyeType eye           = (EyeType)eyeIndex;
                        EyeTexture eyeTexture = eyeTextures[eyeIndex];

                        if (eyeIndex == 0)
                        {
                            layerEyeFov.RenderPoseLeft = eyePoses[0];
                        }
                        else
                        {
                            layerEyeFov.RenderPoseRight = eyePoses[1];
                        }

                        // Update the render description at each frame, as the HmdToEyeOffset can change at runtime.
                        eyeTexture.RenderDescription = OVR.GetRenderDesc(sessionPtr, eye, hmdDesc.DefaultEyeFov[eyeIndex]);

                        // Retrieve the index of the active texture
                        int textureIndex;
                        result = eyeTexture.SwapTextureSet.GetCurrentIndex(out textureIndex);
                        WriteErrorDetails(OVR, result, "Failed to retrieve texture swap chain current index.");

                        immediateContext.OutputMerger.SetRenderTargets(eyeTexture.DepthStencilView, eyeTexture.RenderTargetViews[textureIndex]);
                        immediateContext.ClearRenderTargetView(eyeTexture.RenderTargetViews[textureIndex], Color.Black);
                        immediateContext.ClearDepthStencilView(eyeTexture.DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                        immediateContext.Rasterizer.SetViewport(eyeTexture.Viewport);

                        // Retrieve the eye rotation quaternion and use it to calculate the LookAt direction and the LookUp direction.
                        Quaternion rotationQuaternion = SharpDXHelpers.ToQuaternion(eyePoses[eyeIndex].Orientation);
                        Matrix rotationMatrix         = Matrix.RotationQuaternion(rotationQuaternion);
                        Vector3 lookUp = Vector3.Transform(new Vector3(0, -1, 0), rotationMatrix).ToVector3();
                        Vector3 lookAt = Vector3.Transform(new Vector3(0, 0, 1), rotationMatrix).ToVector3();

                        Vector3 viewPosition = position - eyePoses[eyeIndex].Position.ToVector3();

                        Matrix world      = Matrix.Scaling(0.1f) * Matrix.RotationX(timeSinceStart / 10f) * Matrix.RotationY(timeSinceStart * 2 / 10f) * Matrix.RotationZ(timeSinceStart * 3 / 10f);
                        Matrix viewMatrix = Matrix.LookAtLH(viewPosition, viewPosition + lookAt, lookUp);

                        Matrix projectionMatrix = OVR.Matrix4f_Projection(eyeTexture.FieldOfView, 0.1f, 100.0f, ProjectionModifier.LeftHanded).ToMatrix();
                        projectionMatrix.Transpose();

                        Matrix worldViewProjection = world * viewMatrix * projectionMatrix;
                        worldViewProjection.Transpose();

                        // Update the transformation matrix.
                        immediateContext.UpdateSubresource(ref worldViewProjection, contantBuffer);

                        // Draw the cube
                        immediateContext.Draw(m_vertices.Length / 2, 0);

                        // Commits any pending changes to the TextureSwapChain, and advances its current index
                        result = eyeTexture.SwapTextureSet.Commit();
                        WriteErrorDetails(OVR, result, "Failed to commit the swap chain texture.");
                    }


                    result = OVR.SubmitFrame(sessionPtr, 0L, IntPtr.Zero, ref layerEyeFov);
                    WriteErrorDetails(OVR, result, "Failed to submit the frame of the current layers.");

                    immediateContext.CopyResource(mirrorTextureD3D, backBuffer);
                    swapChain.Present(0, PresentFlags.None);
                });
                #endregion
            }
            finally
            {
                if (immediateContext != null)
                {
                    immediateContext.ClearState();
                    immediateContext.Flush();
                }

                // Release all resources
                Dispose(inputLayout);
                Dispose(contantBuffer);
                Dispose(vertexBuffer);
                Dispose(shaderSignature);
                Dispose(pixelShader);
                Dispose(pixelShaderByteCode);
                Dispose(vertexShader);
                Dispose(vertexShaderByteCode);
                Dispose(mirrorTextureD3D);
                Dispose(mirrorTexture);
                Dispose(eyeTextures[0]);
                Dispose(eyeTextures[1]);
                Dispose(immediateContext);
                Dispose(depthStencilState);
                Dispose(depthStencilView);
                Dispose(depthBuffer);
                Dispose(backBufferRenderTargetView);
                Dispose(backBuffer);
                Dispose(swapChain);
                Dispose(factory);

                // Disposing the device, before the hmd, will cause the hmd to fail when disposing.
                // Disposing the device, after the hmd, will cause the dispose of the device to fail.
                // It looks as if the hmd steals ownership of the device and destroys it, when it's shutting down.
                // device.Dispose();
                OVR.Destroy(sessionPtr);
            }
        }
Example #39
0
		public void LoadResources()
		{
#if DEBUG
			RC.WriteLine(ConsoleThemeColor.SubText3, "RenderContext [" + m_Index + "]: Load Resources, Mode (" + m_Form.ClientSize.Width + "x" + m_Form.ClientSize.Height + ")");
#endif
			if (m_Disposed == true)
			{
				m_BackBuffer = Texture2D.FromSwapChain<Texture2D>(m_SwapChain, 0);
				m_RenderView = new RenderTargetView(GameEnvironment.Device, m_BackBuffer);

				#region Create Depth Buffer

				m_DepthBuffer = new Texture2D(GameEnvironment.Device, new Texture2DDescription()
				{
					Width = m_Form.ClientSize.Width,
					Height = m_Form.ClientSize.Height,
					MipLevels = 1,
					ArraySize = 1,
					Format = Format.D32_Float,
					SampleDescription = new SampleDescription(1, 0),
					Usage = ResourceUsage.Default,
					BindFlags = BindFlags.DepthStencil,
					CpuAccessFlags = CpuAccessFlags.None,
					OptionFlags = ResourceOptionFlags.None
				});

				m_DepthView = new DepthStencilView(GameEnvironment.Device, m_DepthBuffer, new DepthStencilViewDescription()
				{
					Format = Format.D32_Float,
					Dimension = DepthStencilViewDimension.Texture2D,
					MipSlice = 0
				});

				m_DepthState = DepthStencilState.FromDescription(GameEnvironment.Device, new DepthStencilStateDescription()
				{
					IsDepthEnabled = true,
					DepthWriteMask = DepthWriteMask.All,
					DepthComparison = Comparison.LessEqual, // Comparison.LessEqual,
					IsStencilEnabled = false,
					StencilReadMask = 0xff,
					StencilWriteMask = 0xff,

					BackFace = new DepthStencilOperationDescription()
					{
						Comparison = Comparison.Always,
						DepthFailOperation = StencilOperation.Decrement,
						FailOperation = StencilOperation.Keep,
						PassOperation = StencilOperation.Keep
					},

					FrontFace = new DepthStencilOperationDescription()
					{
						Comparison = Comparison.Always,
						DepthFailOperation = StencilOperation.Increment,
						FailOperation = StencilOperation.Keep,
						PassOperation = StencilOperation.Keep
					}
				});

				#endregion

				m_Disposed = false; 
			}
		}
Example #40
0
        private void InitializeDepthBuffer()
        {
            TryDisposing(_depthStencilView);
            TryDisposing(_depthBuffer);

            _depthStencilState = DepthStencilState.FromDescription(_device, new DepthStencilStateDescription
                                                                                {
                                                                                    IsDepthEnabled = true,
                                                                                    DepthComparison =
                                                                                        Comparison.LessEqual
                                                                                });

            _depthBuffer = new Texture2D(_device, new Texture2DDescription
                                                      {
                                                          Width = _form.ClientSize.Width,
                                                          Height = _form.ClientSize.Height,
                                                          Usage = ResourceUsage.Default,
                                                          BindFlags = BindFlags.DepthStencil,
                                                          ArraySize = 1,
                                                          CpuAccessFlags = CpuAccessFlags.None,
                                                          Format = Format.D32_Float,
                                                          MipLevels = 1,
                                                          OptionFlags = ResourceOptionFlags.None,
                                                          SampleDescription = new SampleDescription(1, 0)
                                                      });

            _depthStencilView = new DepthStencilView(_device, _depthBuffer);
        }
Example #41
0
        public void Initialize(DeviceContextHolder holder) {
            foreach (var split in Splits) {
                split.Buffer.Resize(holder, _mapSize, _mapSize);
            }

            _rasterizerState = RasterizerState.FromDescription(holder.Device, new RasterizerStateDescription {
                CullMode = CullMode.Front,
                FillMode = FillMode.Solid,
                IsAntialiasedLineEnabled = false,
                IsDepthClipEnabled = true,
                DepthBias = 1000,
                DepthBiasClamp = 0f,
                SlopeScaledDepthBias = 1f
            });

            _depthStencilState = DepthStencilState.FromDescription(holder.Device, new DepthStencilStateDescription {
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Greater,
                IsDepthEnabled = true,
                IsStencilEnabled = false
            });
        }
 private static void SetDeviceState(GraphicsDevice device, BlendState blendState, DepthStencilState depthStencilState, RasterizerState rasterizerState)
 => SetDeviceState(device, blendState, depthStencilState, rasterizerState, SamplerState.LinearWrap);
Example #43
0
 public MaterialPass()
 {
     ShaderEntry = new ShaderEntry();
     RasterizerStates = new RasterizerState();
     BlendStates = new BlendState();
     DepthStencilStates = new DepthStencilState();
 }
Example #44
0
            public void Render(SpriteBatch spriteBatch, Environment env, GameTime time, Rectangle mapDest, float posLerp)
            {
                Vector2 currentPos = new Vector2(env.agentPosX_, env.agentPosY_);

                if (LastPos.X == float.NaN)
                {
                    LastPos = currentPos;
                    CurPos  = LastPos;
                }
                if (posLerp == 0.0f)
                {
                    LastPos = CurPos;
                    CurPos  = currentPos;
                }
                if (System.Math.Abs(LastPos.X - currentPos.X + LastPos.Y - currentPos.Y) > 1.5f)
                {
                    posLerp = 1.0f;
                }
                Vector2 lerpPos = Vector2.Lerp(LastPos, currentPos, posLerp);

                if (posLerp > 0.5f)
                {
                    System.Console.WriteLine();
                }

                int   tile;
                float x = -Environment.mazeSize_ * 0.5f, z = -Environment.mazeSize_ * 0.5f;

                Matrix worldTransform    = Matrix.Identity;
                Matrix wvp;

                ModelMesh   wallMesh     = Wall.Meshes[0];
                ModelMesh   floorMesh    = FloorTile.Meshes[0];
                ModelMesh   dirtMesh     = Dirt.Meshes[0];
                Effect      wallEffect   = wallMesh.Effects[0];
                BasicEffect floorEffect  = (BasicEffect)floorMesh.Effects[0];
                Effect      dirtEffect   = dirtMesh.Effects[0];

                DepthStencilState oldDss = GraphicsDevice.DepthStencilState;
                RasterizerState   oldRs  = GraphicsDevice.RasterizerState;

                GraphicsDevice.DepthStencilState = dss;
                GraphicsDevice.RasterizerState   = rs;
                GraphicsDevice.SamplerStates[0]  = ss;

                for (int i = 0; i < Environment.mazeSize_; ++i)
                {
                    for (int j = 0; j < Environment.mazeSize_; ++j)
                    {
                        tile = env.maze_[i][j];
                        worldTransform.M41 = x + i;
                        worldTransform.M42 = 0.0f;
                        worldTransform.M43 = z + j;
                        Matrix.Multiply(ref worldTransform, ref Camera.ViewProj, out wvp);
                        if (tile == -1)
                        {
                            wallEffect.Parameters["WorldViewProj"].SetValue(wvp);
                            wallMesh.Draw();
                        }
                        else
                        {
                            floorEffect.Parameters["WorldViewProj"].SetValue(wvp);
                            floorEffect.DiffuseColor = Vector3.Lerp((Vector3)floorEffect.Tag, Vector3.Zero, tile * MAX_DIRT);
                            floorMesh.Draw();
                            ////worldTransform.M42 = MathHelper.Lerp(0.04f, 0.8f, tile * MAX_DIRT);
                            ////Matrix.Multiply(ref worldTransform, ref Camera.ViewProj, out wvp);
                            //dirtEffect.Parameters["WorldViewProj"].SetValue(wvp);
                            //dirtMesh.Draw();
                        }
                    }
                }

                worldTransform.M41 = x + lerpPos.X;
                worldTransform.M42 = 0.0f;
                worldTransform.M43 = z + lerpPos.Y + 0.5f;
                float rotation           = 0f;
                Color col                = Color.White;

                switch (env.preAction_)
                {
                case ActionType.actIDLE:
                    rotation = LastRot;
                    col      = Color.Yellow;
                    break;

                case ActionType.actSUCK:
                    col = Color.Green;
                    break;

                case ActionType.actUP:
                    if (env.isJustBump)
                    {
                        col = Color.Red;
                    }
                    break;

                case ActionType.actRIGHT:
                    if (env.isJustBump)
                    {
                        col = Color.Red;
                    }
                    rotation = MathHelper.PiOver2;
                    break;

                case ActionType.actDOWN:
                    if (env.isJustBump)
                    {
                        col = Color.Red;
                    }
                    rotation = MathHelper.Pi;
                    break;

                case ActionType.actLEFT:
                    if (env.isJustBump)
                    {
                        col = Color.Red;
                    }
                    rotation = -MathHelper.PiOver2;
                    break;
                }

                var val1 = (float)System.Math.Cos(rotation);
                var val2 = (float)System.Math.Sin(rotation);

                worldTransform.M11 = val1;
                worldTransform.M13 = -val2;
                worldTransform.M31 = val2;
                worldTransform.M33 = val1;
                ModelMesh cleanerMesh = Cleaner.Meshes[0];

                Matrix.Multiply(ref worldTransform, ref Camera.ViewProj, out wvp);
                foreach (BasicEffect effect in cleanerMesh.Effects)
                {
                    effect.DiffuseColor = (Vector3)effect.Tag * col.ToVector3();
                    effect.Parameters["WorldViewProj"].SetValue(wvp);
                }
                cleanerMesh.Draw();

                GraphicsDevice.DepthStencilState = oldDss;
                GraphicsDevice.RasterizerState   = oldRs;
            }
Example #45
0
		/// <summary>
		/// Creates pipeline state factory
		/// </summary>
		public StateFactory CreateFactory ( Type type, Primitive primitive, VertexInputElement[] vertexInputElements, BlendState blendState, RasterizerState rasterizerState, DepthStencilState depthStencilState )
		{
			return CreateFactory( type, (ps,i) => { 
					ps.Primitive = primitive;
					ps.VertexInputElements	=	vertexInputElements; 
					ps.BlendState			=	blendState;
					ps.RasterizerState		=	rasterizerState;
					ps.DepthStencilState	=	depthStencilState;
				});
		}
Example #46
0
 public RenderStates()
 {
     RasterizerState   = GraphicsManager.DefaultRasterizerState;
     BlendState        = BlendState.AlphaBlend;
     DepthStencilState = DepthStencilState.Default;
 }
Example #47
0
        private void createDepthBuffer()
        {
            Texture2DDescription depthdesc = new Texture2DDescription();
            depthdesc.BindFlags = BindFlags.DepthStencil;
            depthdesc.Format = Format.D32_Float_S8X24_UInt;
            depthdesc.Width = WindowWidth;
            depthdesc.Height = WindowHeight;
            depthdesc.MipLevels = 1;
            depthdesc.SampleDescription = new SampleDescription(1, 0);
            depthdesc.Usage = ResourceUsage.Default;
            depthdesc.OptionFlags = ResourceOptionFlags.None;
            depthdesc.CpuAccessFlags = CpuAccessFlags.None;
            depthdesc.ArraySize = 1;

            DepthTexture = new Texture2D(D3DDevice, depthdesc);

            SampleDepthView = new DepthStencilView(D3DDevice, DepthTexture);

            DepthStencilStateDescription depthStencilDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,

                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },

                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            depthStencilState = DepthStencilState.FromDescription(D3DDevice, depthStencilDesc);

            DepthStencilStateDescription disabledDepthStencilDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less,

                IsStencilEnabled = true,
                StencilReadMask = 0xFF,
                StencilWriteMask = 0xFF,

                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Increment,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                },

                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Decrement,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Always
                }
            };

            disabledDepthStencilState = DepthStencilState.FromDescription(D3DDevice, disabledDepthStencilDesc);
        }
        public override void Attach(IRenderHost host)
        {
            /// --- attach
            this.renderTechnique = Techniques.RenderCubeMap;
            base.Attach(host);

            /// --- get variables               
            this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique);
            this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name);
            this.effectTransforms = new EffectTransformVariables(this.effect);

            /// -- attach cube map 
            if (this.Filename != null)
            {
                /// -- attach texture
                using (var texture = Texture2D.FromFile<Texture2D>(this.Device, this.Filename))
                {
                    this.texCubeMapView = new ShaderResourceView(this.Device, texture);
                }
                this.texCubeMap = effect.GetVariableByName("texCubeMap").AsShaderResource();
                this.texCubeMap.SetResource(this.texCubeMapView);
                this.bHasCubeMap = effect.GetVariableByName("bHasCubeMap").AsScalar();
                this.bHasCubeMap.Set(true);

                /// --- set up geometry
                var sphere = new MeshBuilder(false,true,false);
                sphere.AddSphere(new Vector3(0, 0, 0));
                this.geometry = sphere.ToMeshGeometry3D();

                /// --- set up vertex buffer
                this.vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, CubeVertex.SizeInBytes, this.geometry.Positions.Select((x, ii) => new CubeVertex() { Position = new Vector4(x, 1f) }).ToArray());

                /// --- set up index buffer
                this.indexBuffer = Device.CreateBuffer(BindFlags.IndexBuffer, sizeof(int), geometry.Indices.Array);

                /// --- set up rasterizer states
                var rasterStateDesc = new RasterizerStateDescription()
                {
                    FillMode = FillMode.Solid,
                    CullMode = CullMode.Back,
                    IsMultisampleEnabled = true,
                    IsAntialiasedLineEnabled = true,
                    IsFrontCounterClockwise = false,
                };
                this.rasterState = new RasterizerState(this.Device, rasterStateDesc);

                /// --- set up depth stencil state
                var depthStencilDesc = new DepthStencilStateDescription()
                {
                    DepthComparison = Comparison.LessEqual,
                    DepthWriteMask = global::SharpDX.Direct3D11.DepthWriteMask.All,
                    IsDepthEnabled = true,
                };
                this.depthStencilState = new DepthStencilState(this.Device, depthStencilDesc);
            }

            /// --- flush
            this.Device.ImmediateContext.Flush();
        }
Example #49
0
        private void CreateStencilState()
        {
            var depthStencilStateDescription = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };

            mDepthStencilState = DepthStencilState.FromDescription(Device, depthStencilStateDescription);
            Device.OutputMerger.DepthStencilState = mDepthStencilState;
        }
Example #50
0
        /// <summary>
        /// Initialize everything D3D in here
        ///  Leave pretty empty for now.
        /// </summary>
        protected virtual void InitD3D()
        {
            // Set up rendering mode description (width, height, frame rate, color format)
            var modeDescription = new ModeDescription(0, 0, new SlimDX.Rational(60, 1), Format.R8G8B8A8_UNorm);

            // Set up swap chain description
            var swapChainDesc = new SwapChainDescription
            {
                BufferCount = 2,
                Usage = Usage.RenderTargetOutput,
                OutputHandle = Handle,
                IsWindowed = true,
                ModeDescription = modeDescription,
                SampleDescription = new SampleDescription(1, 0),
                Flags = SwapChainFlags.AllowModeSwitch,
                SwapEffect = SwapEffect.Discard
            };

            // Create our device and swap chain
            SlimDX.Direct3D11.Device.CreateWithSwapChain
            (
                DriverType.Hardware,
                DeviceCreationFlags.None,
                swapChainDesc,
                out Device,
                out SwapChain
            );

            // Obtain our device context (Immediate context)
            ImmediateContext = Device.ImmediateContext;

            // Prevent DXGI handling of alt+enter...
            using (var factory = SwapChain.GetParent<Factory>())
            {
                factory.SetWindowAssociation(Handle, WindowAssociationFlags.IgnoreAltEnter);
            }

            // Instead, handle the command ourselves
            KeyDown += (sender, e) =>
            {
                if (e.Alt && e.KeyCode == Keys.Enter)
                {
                    SwapChain.IsFullScreen = !SwapChain.IsFullScreen;
                }
            };

            // Add resize handling...
            UserResized += (sender, e) =>
            {
                OnResize(e);
            };

            // Set up viewport, render target (back buffer on swap chain), and render target view
            Viewport = new Viewport(0.0f, 0.0f, ClientSize.Width, ClientSize.Height, 0.0f, 1.0f);
            ImmediateContext.Rasterizer.SetViewports(Viewport);
            using (var resource = SlimDX.Direct3D11.Resource.FromSwapChain<Texture2D>(SwapChain, 0))
            {
                RenderTargetView = new RenderTargetView(Device, resource);
            }

            // Create the depth/stencil buffer and view
            // TODO KAM: On resize the window, do you need to resize the depth/stencil view?
            var depthBufferDesc = new Texture2DDescription
            {
                ArraySize = 1,
                BindFlags = BindFlags.DepthStencil,
                CpuAccessFlags = CpuAccessFlags.None,
                Format = Format.D32_Float,
                Height = ClientSize.Height,
                Width = ClientSize.Width,
                MipLevels = 1,
                OptionFlags = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0),
                Usage = ResourceUsage.Default
            };

            DepthStencilBuffer = new Texture2D(Device, depthBufferDesc);

            var depthStencilViewDesc = new DepthStencilViewDescription
            {
                ArraySize = 0,
                Format = Format.D32_Float,
                Dimension = DepthStencilViewDimension.Texture2D,
                MipSlice = 0,
                Flags = 0,
                FirstArraySlice = 0
            };

            DepthStencilView = new DepthStencilView(Device, DepthStencilBuffer, depthStencilViewDesc);

            ImmediateContext.OutputMerger.SetTargets(DepthStencilView, RenderTargetView);

            // Set up the depth/stencil state description
            var dsStateDesc = new DepthStencilStateDescription
            {
                IsDepthEnabled = true,
                IsStencilEnabled = false,
                DepthWriteMask = DepthWriteMask.All,
                DepthComparison = Comparison.Less
            };

            DepthStencilState = DepthStencilState.FromDescription(Device, dsStateDesc);

            // Set depth/stencil state for the output merger
            ImmediateContext.OutputMerger.DepthStencilState = DepthStencilState;
        }
Example #51
0
 /// <summary>
 /// Sets the depth-stencil state of the output-merger stage. See <see cref="Render+states"/> to learn how to use it.
 /// </summary>
 /// <param name="depthStencilState">a depth-stencil state</param>
 /// <param name="stencilReference">Reference value to perform against when doing a depth-stencil test.</param>
 private void SetDepthStencilStateImpl(DepthStencilState depthStencilState, int stencilReference = 0)
 {
     NativeDeviceContext.OutputMerger.SetDepthStencilState(depthStencilState != null ? (SharpDX.Direct3D11.DepthStencilState)depthStencilState.NativeDeviceChild : null, stencilReference);
 }
        void CreateDepthStencilState(XmlNode node)
        {

            bool depthEnabled = true;
            bool stencilEnabled = false;
            Comparison depthComparison = Comparison.LessEqual;
            Comparison frontComparison = Comparison.LessEqual;
            StencilOperation frontDepthFailOp = StencilOperation.Keep;
            StencilOperation frontFailOp = StencilOperation.Keep;
            StencilOperation frontPassOp = StencilOperation.Replace;
            Comparison backComparison = Comparison.LessEqual;
            StencilOperation backDepthFailOp = StencilOperation.Keep;
            StencilOperation backFailOp = StencilOperation.Keep;
            StencilOperation backPassOp = StencilOperation.Replace;

            if (node.Attributes["default"] != null)
            {
                if (GetBoolean(node.Attributes["default"].Value))
                {
                    defaultDepthStencil = node.Attributes["name"].Value;
                }
            }


            foreach (XmlNode parameter in node.ChildNodes)
            {
                switch (parameter.Name.ToLower())
                {
                    case "depthenabled":
                        depthEnabled = GetBoolean(parameter.InnerText);
                        break;
                    case "stencilenabled":
                        stencilEnabled = GetBoolean(parameter.InnerText);
                        break;
                    case "depthcomparison":
                        depthComparison = GetComparison(parameter.InnerText);
                        break;
                    case "frontface":
                        GetFaceForDepthStencil(parameter, out frontComparison,
                            out frontDepthFailOp, out frontFailOp, out frontPassOp);
                        break;
                    case "backface":
                        GetFaceForDepthStencil(parameter, out backComparison,
                            out backDepthFailOp, out backFailOp, out backPassOp);
                        break;
                    default:
                        throw new Exception("Uknown parameter on depthstencil state");
                }              
            }

            DepthStencilState RS = new DepthStencilState(depthEnabled, stencilEnabled,
               depthComparison, frontComparison, frontDepthFailOp, frontFailOp, frontPassOp,
               backComparison, backDepthFailOp, backFailOp, backPassOp);

            depthStencilStates.Add(node.Attributes["name"].Value, RS);
        }
 public override void Initialize()
 {
     base.Initialize();
     plStruct = new PointLightStruct[maxLights];
     pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true);
     string path = @"R:\Users\Rox Cox\Documents\Visual Studio 2013\Projects\LightingEngine_v2\LightingEngine_v2\LightingD3D11\HLSL\";
     ShaderFlags flags = ShaderFlags.Debug | ShaderFlags.EnableStrictness | ShaderFlags.PackMatrixRowMajor;
     using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(path + "forward.hlsl", "ForwardPS", "ps_5_0", flags, EffectFlags.None, null, new IncludeFX(path)))
     {
         PS_PointLights = new PixelShader(Renderer.Device, bytecode);
     }
     DepthStencilStateDescription dssdesc = States.DepthDefault();
     dssdesc.DepthComparison = Comparison.GreaterEqual;
     dss = DepthStencilState.FromDescription(Renderer.Device, dssdesc);
 }
Example #54
0
 protected override void PlatformSetDepthStencilState(DepthStencilState depthStencilState)
 {
     ((OpenGLESDepthStencilState)depthStencilState).Apply();
 }
Example #55
0
        public static void Initialize(Device device)
        {
            {
                var blendStateDescription = new BlendStateDescription();
                blendStateDescription.RenderTargets[0].BlendEnable           = false;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
                blendStateDescription.RenderTargets[1].BlendEnable           = false;
                blendStateDescription.RenderTargets[1].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[2].BlendEnable           = false;
                blendStateDescription.RenderTargets[2].RenderTargetWriteMask = ColorWriteMaskFlags.None;
                blendStateDescription.RenderTargets[3].BlendEnable           = false;
                blendStateDescription.RenderTargets[3].RenderTargetWriteMask = ColorWriteMaskFlags.None;

                m_BlendStates[(int)BlendType.None] = BlendState.FromDescription(device, blendStateDescription);

                blendStateDescription.RenderTargets[0].BlendEnable           = true;
                blendStateDescription.RenderTargets[0].BlendOperation        = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].BlendOperationAlpha   = BlendOperation.Add;
                blendStateDescription.RenderTargets[0].DestinationBlend      = BlendOption.One;
                blendStateDescription.RenderTargets[0].DestinationBlendAlpha = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlend           = BlendOption.One;
                blendStateDescription.RenderTargets[0].SourceBlendAlpha      = BlendOption.One;
                blendStateDescription.RenderTargets[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;

                m_BlendStates[(int)BlendType.Additive] = BlendState.FromDescription(device, blendStateDescription);
            }

            {
                var depthStencilStateDescription = new DepthStencilStateDescription();
                depthStencilStateDescription.DepthComparison  = Comparison.Always;
                depthStencilStateDescription.DepthWriteMask   = DepthWriteMask.Zero;
                depthStencilStateDescription.IsDepthEnabled   = false;
                depthStencilStateDescription.IsStencilEnabled = false;

                m_DepthStencilStates[(int)DepthConfigurationType.NoDepth] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthComparison = Comparison.LessEqual;
                depthStencilStateDescription.DepthWriteMask  = DepthWriteMask.All;
                depthStencilStateDescription.IsDepthEnabled  = true;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthWriteCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);

                depthStencilStateDescription.DepthWriteMask = DepthWriteMask.Zero;

                m_DepthStencilStates[(int)DepthConfigurationType.DepthCompare] = DepthStencilState.FromDescription(device, depthStencilStateDescription);
            }
        }
Example #56
0
        public void DrawWater(GraphicsDevice device,
                              float time,
                              Shader effect,
                              Matrix viewMatrix,
                              Matrix reflectionViewMatrix,
                              Matrix projectionMatrix,
                              Vector3 windDirection,
                              Camera camera,
                              ChunkManager chunks)
        {
            if (DrawReflections)
            {
                effect.CurrentTechnique = effect.Techniques[Shader.Technique.Water];
            }
            else
            {
                effect.CurrentTechnique = effect.Techniques[Shader.Technique.WaterTextured];
            }

            BlendState        origState      = device.BlendState;
            DepthStencilState origDepthState = device.DepthStencilState;

            device.DepthStencilState = DepthStencilState.Default;

            device.BlendState = BlendState.NonPremultiplied;


            Matrix worldMatrix = Matrix.Identity;

            effect.World          = worldMatrix;
            effect.View           = viewMatrix;
            effect.CameraPosition = camera.Position;
            if (DrawReflections)
            {
                effect.ReflectionView = reflectionViewMatrix;
            }

            effect.Projection = projectionMatrix;

            if (DrawReflections)
            {
                effect.WaterReflectionMap = ReflectionMap;
            }

            effect.WaterShoreGradient = ShoreMap;
            effect.Time           = time;
            effect.WindDirection  = windDirection;
            effect.CameraPosition = camera.Position;


            foreach (KeyValuePair <LiquidType, LiquidAsset> asset in LiquidAssets)
            {
                effect.WaveLength = asset.Value.WaveLength;
                effect.WaveHeight = asset.Value.WaveHeight;
                if (DrawReflections)
                {
                    effect.WaterBumpMap     = asset.Value.BumpTexture;
                    effect.WaterReflectance = asset.Value.Reflection;
                }
                effect.MainTexture     = asset.Value.BaseTexture;
                effect.WaterOpacity    = asset.Value.Opactiy;
                effect.MinWaterOpacity = asset.Value.MinOpacity;
                effect.RippleColor     = new Color(asset.Value.RippleColor);


                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    foreach (var chunk in chunks.ChunkData.GetChunkEnumerator())
                    {
                        if (chunk.IsVisible)
                        {
                            //chunk.PrimitiveMutex.WaitOne();
                            chunk.Liquids[asset.Key].Render(device);
                            //chunk.PrimitiveMutex.ReleaseMutex();
                        }
                    }
                }
            }
            device.BlendState        = origState;
            device.DepthStencilState = origDepthState;
        }
 public GraphicsPipelineStackNode(string DrawStackID, string TargetID, Effect ActiveEffect = null, DepthStencilState DepthState = null, Color?ClearColor = null) : base(TargetID, ActiveEffect, DepthState, ClearColor)
 {
     _drawStackID = DrawStackID;
 }
        // Example using async
        protected override void CreateDeviceDependentResources(Common.DeviceManager deviceManager)
        {
            base.CreateDeviceDependentResources(deviceManager);

            RemoveAndDispose(ref fpsRenderer);
            RemoveAndDispose(ref cubeRenderer);
            RemoveAndDispose(ref textRenderer);

            RemoveAndDispose(ref vertexShader);
            RemoveAndDispose(ref vertexLayout);
            RemoveAndDispose(ref pixelShader);

            var device = deviceManager.Direct3DDevice;

            #region Compile shaders
            // Compile Vertex Shader and create vertex InputLayout
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\VS.hlsl", "VSMain", "vs_5_0"))
            {
                vertexShader = new VertexShader(device, bytecode);
                vertexLayout = ToDispose(new InputLayout(device,
                                                         bytecode.GetPart(ShaderBytecodePart.InputSignatureBlob).Data,
                                                         new[]
                {
                    // "SV_Position" = vertex coordinate in object space
                    new InputElement("SV_Position", 0, Format.R32G32B32_Float, 0, 0),
                    // "NORMAL" = the vertex normal
                    new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                    // "COLOR"
                    new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 24, 0),
                    // "UV"
                    new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0),
                    // "BLENDINDICES"
                    new InputElement("BLENDINDICES", 0, Format.R32G32B32A32_UInt, 36, 0),
                    // "BLENDWEIGHT"
                    new InputElement("BLENDWEIGHT", 0, Format.R32G32B32A32_Float, 52, 0),
                }));
            }

            // Compile pixel shader
            using (var bytecode = HLSLCompiler.CompileFromFile(@"Shaders\SimplePS.hlsl", "PSMain", "ps_5_0"))
                pixelShader = ToDispose(new PixelShader(device, bytecode));
            #endregion

            #region Create constant buffers
            // Create constant buffers

            // Create the constant buffer that will
            // store our worldViewProjection matrix
            perObjectBuffer = ToDispose(new SharpDX.Direct3D11.Buffer(device, Utilities.SizeOf <ConstantBuffers.PerObject>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per frame constant buffer
            // lighting / camera position
            perFrameBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerFrame>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per material constant buffer
            perMaterialBuffer = ToDispose(new Buffer(device, Utilities.SizeOf <ConstantBuffers.PerMaterial>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            // Create the per armature/skeletong constant buffer
            perArmatureBuffer = ToDispose(new Buffer(device, ConstantBuffers.PerArmature.Size(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0));

            #endregion

            #region Create pipeline state variables
            // Configure the depth buffer to discard pixels that are
            // further than the current pixel.
            depthStencilState = ToDispose(new DepthStencilState(device,
                                                                new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,   // enable depth?
                DepthComparison  = Comparison.Less,
                DepthWriteMask   = SharpDX.Direct3D11.DepthWriteMask.All,
                IsStencilEnabled = false,   // enable stencil?
                StencilReadMask  = 0xff,    // 0xff (no mask)
                StencilWriteMask = 0xff,    // 0xff (no mask)
            }));

            rsCullBack = ToDispose(new RasterizerState(device, new RasterizerStateDescription
            {
                CullMode = CullMode.Back,
                IsFrontCounterClockwise = false,
                FillMode = FillMode.Solid,
            }));
            #endregion


            #region Create Renderers
            cubeRenderer = new CubeRenderer();
            cubeRenderer.Initialize(this);

            textRenderer = ToDispose(new TextRenderer("Calibri", SharpDX.Color.Black, new Point(20, 100), 48, 800));
            textRenderer.Initialize(this);

            fpsRenderer = ToDispose(new FpsRenderer());
            fpsRenderer.Initialize(this);
            #endregion

            clock.Start();
        }
        public override void Initialize()
        {
            base.Initialize();
            plStruct = new PointLightStruct[maxLights];
            pLightBuffer = new StructuredBuffer<PointLightStruct>(maxLights, false, true);
            cBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.PixelShader, 0);
            cBuffer.Semantics.Add(Semantic.Projection);
            cBuffer.Semantics.Add(Semantic.CameraNearFar);
            GBuffer = new GBuffer(Renderer);

            BlendStateDescription disabledBlendDesc = States.BlendDefault();
            BlendStateDescription additiveDesc = States.BlendDefault();
            additiveDesc.RenderTargets[0] = new RenderTargetBlendDescription()
            {
                BlendEnable = true,
                SourceBlend = BlendOption.One,
                DestinationBlend = BlendOption.One,
                BlendOperation = BlendOperation.Add,
                SourceBlendAlpha = BlendOption.One,
                DestinationBlendAlpha = BlendOption.One,
                BlendOperationAlpha = BlendOperation.Add,
                RenderTargetWriteMask = ColorWriteMaskFlags.All,
            };
            DepthStencilStateDescription defaultDepthDesc = States.DepthDefault();
            defaultDepthDesc.DepthComparison = Comparison.GreaterEqual;
            DepthStencilStateDescription equalDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = true,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.GreaterEqual,
                IsStencilEnabled = true,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0xFF,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal,
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation = StencilOperation.Keep,
                    Comparison = Comparison.Equal,
                }
            };
            DepthStencilStateDescription writeDesc = new DepthStencilStateDescription()
            {
                IsDepthEnabled = false,
                DepthWriteMask = DepthWriteMask.Zero,
                DepthComparison = Comparison.GreaterEqual,
                IsStencilEnabled = true,
                StencilWriteMask = 0xFF,
                StencilReadMask = 0xFF,
                FrontFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Replace,
                    DepthFailOperation = StencilOperation.Replace,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always,
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation = StencilOperation.Replace,
                    DepthFailOperation = StencilOperation.Replace,
                    PassOperation = StencilOperation.Replace,
                    Comparison = Comparison.Always,
                }
            };
            RasterizerStateDescription rsDesc = States.RasterizerDefault();

            mGeometryBlendState = BlendState.FromDescription(Renderer.Device, disabledBlendDesc);
            mLightingBlendState = BlendState.FromDescription(Renderer.Device, additiveDesc);
            mDepthState = DepthStencilState.FromDescription(Renderer.Device, defaultDepthDesc);
            mEqualStencilState = DepthStencilState.FromDescription(Renderer.Device, equalDesc);
            mWriteStencilState = DepthStencilState.FromDescription(Renderer.Device, writeDesc);
            mRasterizerState = RasterizerState.FromDescription(Renderer.Device, rsDesc);

            InitializeBuffers();
            InitializeShaders();
        }
Example #60
0
        public static RenderTargetSet CreateRenderTargetSet( Device device, int width, int height, Format format, int numSurfaces, bool needsDepth )
        {
            RenderTargetSet rt = new RenderTargetSet();

            rt.m_Descriptor = new RenderTargetDescriptor()
            {
                m_Format = format,
                m_HasDepth = needsDepth,
                m_Height = height,
                m_NumSurfaces = numSurfaces,
                m_Width = width
            };

            rt.m_NumRTs = numSurfaces;
            for (int i = 0; i < numSurfaces; ++i)
            {
                rt.m_RenderTargets[i] = TextureObject.CreateTexture(device, width, height, 1, format, false, true);
            }
            
            if (needsDepth)
            {
                rt.m_DepthStencil = TextureObject.CreateTexture(device, width, height, 1, Format.R32_Typeless, true, false);
            }

            rt.m_Viewport = new Viewport(0, 0, width, height, 0.0f, 1.0f);

            if (m_DepthStencilState == null)
            {
                DepthStencilStateDescription dsStateDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = true,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.All,
                    DepthComparison = Comparison.Less,
                };

                m_DepthStencilState = DepthStencilState.FromDescription(device, dsStateDesc);

                dsStateDesc = new DepthStencilStateDescription()
                {
                    IsDepthEnabled = false,
                    IsStencilEnabled = false,
                    DepthWriteMask = DepthWriteMask.Zero,
                    DepthComparison = Comparison.Always,
                };

                m_DepthStencilStateNoDepth = DepthStencilState.FromDescription(device, dsStateDesc);
            }
            

            return rt;
        }