public override void LoadResources() { if (m_Disposed == true) { m_TextFont.LoadResources(); //SlimDX.D3DCompiler.ShaderBytecode blob = SlimDX.D3DCompiler.ShaderBytecode.CompileFromFile(Helper.ResolvePath(m_ShaderLocation), "fx_4_0", SlimDX.D3DCompiler.ShaderFlags.EnableStrictness, SlimDX.D3DCompiler.EffectFlags.None); m_Effect = new Effect(GameEnvironment.Device, Bytecode); m_Technique = m_Effect.GetTechniqueByName("LinesAndBoxes"); m_Pass_BoxesAndText = m_Technique.GetPassByName("BoxesAndText"); m_Pass_Lines = m_Technique.GetPassByName("Lines"); m_Layout = new InputLayout(GameEnvironment.Device, m_Pass_Lines.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 20, 0), }); m_UiElementsTexture = m_Effect.GetVariableByName("UiElementsTexture").AsResource(); m_UiElementsTexture.SetResource(m_TextFont.TexureView); m_Disposed = false; } }
public void Render(DeviceContext dc, EffectPass pass, Matrix view, Matrix proj) { var position = Particle.Position; Model.World = Matrix.Translation(position); Model.Draw(dc, pass, view, proj); }
public override void LoadResources() { if (m_Disposed == true) { m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); m_Technique = m_Effect.GetTechniqueByName("RenderParticles"); m_ParticlePass_Add = m_Technique.GetPassByName("Add"); m_Layout = new InputLayout(GameEnvironment.Device, m_ParticlePass_Add.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0), new InputElement("INST_POSITION", 0, Format.R32G32B32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement("INST_COLOR", 0, Format.R32G32B32A32_Float, 12, 1, InputClassification.PerInstanceData, 1), }); m_WorldViewProj = m_Effect.GetVariableByName("worldViewProj").AsMatrix(); m_ParticleTexture = m_Effect.GetVariableByName("particle_texture").AsResource(); m_AmpScale = m_Effect.GetVariableByName("ampScale").AsScalar(); m_PartScaleX = m_Effect.GetVariableByName("partScaleX").AsScalar(); m_PartScaleY = m_Effect.GetVariableByName("partScaleY").AsScalar(); m_MaxDistance = m_Effect.GetVariableByName("maxDistance").AsScalar(); m_MinDistance = m_Effect.GetVariableByName("minDistance").AsScalar(); m_ScaleDistance = m_Effect.GetVariableByName("scaleDistance").AsScalar(); m_Disposed = false; } }
public void Render(DeviceContext dc, EffectPass pass, Matrix view, Matrix proj) { var position = Particle.Position; Model.World = Matrix.Scaling(new Vector3(1 + Particle.Mass / 100)) * Matrix.Translation(position); Model.Draw(dc, pass, view, proj); }
public MeshMaterialBinding(Device device, Material material, Mesh mesh) { mDevice = device; mMesh = mesh; mPass = material.GetFirstPass(); mInputLayout = new InputLayout(device, mPass.Description.Signature, mesh.GetInputElements()); }
public ShaderData(Effect shader, string passName) { _passName = passName; _shader = shader; if (shader != null && passName != null) { _effectPass = shader.CurrentTechnique.Passes[passName]; } }
/// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(true, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) { shaderIndex += 1; } if (fresnelEnabled) { shaderIndex += 2; } if (specularEnabled) { shaderIndex += 4; } if (oneLight) { shaderIndex += 8; } shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } return(base.OnApply(shaderPass)); }
public void SwapProgram(string passName) { this._passName = passName; if (passName == null) { return; } this._effectPass = this.Shader.CurrentTechnique.Passes[passName]; }
public void Initialize() { _worldViewProjParam = _shader.Parameters["WorldViewProj"]; _globalColorParam = _shader.Parameters["GlobalColor"]; //Passes _vertexColorPass = _shader.Techniques["VertexColor"].Passes[0]; _globalColorPass = _shader.Techniques["GlobalColor"].Passes[0]; }
/// <summary> /// Show shadows with help of our blur map shader /// </summary> public void RenderShadows() { // Only apply post screen blur if texture is valid and effect are valid if (sceneMapTexture == null || Valid == false || // If the shadow scene map is not yet filled, there is no point // continuing here ... sceneMapTexture.XnaTexture == null) { return; } // Don't use or write to the z buffer BaseGame.Device.DepthStencilState = DepthStencilState.None; // Disable alpha for the first pass BaseGame.Device.BlendState = BlendState.Opaque; if (windowSize != null) { windowSize.SetValue( new float[] { sceneMapTexture.Width, sceneMapTexture.Height }); } if (sceneMap != null) { sceneMap.SetValue(sceneMapTexture.XnaTexture); } effect.CurrentTechnique = effect.Techniques["ScreenAdvancedBlur20"]; // We must have exactly 2 passes! if (effect.CurrentTechnique.Passes.Count != 2) { throw new InvalidOperationException( "This shader should have exactly 2 passes!"); } // Just start pass 0 blurMapTexture.SetRenderTarget(); EffectPass effectPass = effect.CurrentTechnique.Passes[0]; effectPass.Apply(); VBScreenHelper.Render(); blurMapTexture.Resolve(); BaseGame.ResetRenderTarget(false); // Restore z buffer state BaseGame.Device.DepthStencilState = DepthStencilState.Default; // Set u/v addressing back to wrap BaseGame.Device.SamplerStates[0] = SamplerState.LinearWrap; // Restore normal alpha blending //BaseGame.Device.RenderState.BlendFunction = BlendFunction.Add; BaseGame.SetCurrentAlphaMode(BaseGame.AlphaMode.Default); }
/// <summary> /// Read and create a SilverlightEffect /// </summary> protected override SilverlightEffect Read(ContentReader input, SilverlightEffect existingInstance) { int techniquesCount = input.ReadInt32(); EffectTechnique[] techniques = new EffectTechnique[techniquesCount]; for (int techniqueIndex = 0; techniqueIndex < techniquesCount; techniqueIndex++) { int passesCount = input.ReadInt32(); EffectPass[] passes = new EffectPass[passesCount]; for (int passIndex = 0; passIndex < passesCount; passIndex++) { string passName = input.ReadString(); // Vertex shader int vertexShaderByteCodeLength = input.ReadInt32(); byte[] vertexShaderByteCode = input.ReadBytes(vertexShaderByteCodeLength); int vertexShaderParametersLength = input.ReadInt32(); byte[] vertexShaderParameters = input.ReadBytes(vertexShaderParametersLength); // Pixel shader int pixelShaderByteCodeLength = input.ReadInt32(); byte[] pixelShaderByteCode = input.ReadBytes(pixelShaderByteCodeLength); int pixelShaderParametersLength = input.ReadInt32(); byte[] pixelShaderParameters = input.ReadBytes(pixelShaderParametersLength); MemoryStream vertexShaderCodeStream = new MemoryStream(vertexShaderByteCode); MemoryStream pixelShaderCodeStream = new MemoryStream(pixelShaderByteCode); MemoryStream vertexShaderParametersStream = new MemoryStream(vertexShaderParameters); MemoryStream pixelShaderParametersStream = new MemoryStream(pixelShaderParameters); // Instanciate pass SilverlightEffectPass currentPass = new SilverlightEffectPass(passName, GraphicsDeviceManager.Current.GraphicsDevice, vertexShaderCodeStream, pixelShaderCodeStream, vertexShaderParametersStream, pixelShaderParametersStream); passes[passIndex] = currentPass; vertexShaderCodeStream.Dispose(); pixelShaderCodeStream.Dispose(); vertexShaderParametersStream.Dispose(); pixelShaderParametersStream.Dispose(); // Render states int renderStatesCount = input.ReadInt32(); for (int renderStateIndex = 0; renderStateIndex < renderStatesCount; renderStateIndex++) { currentPass.AppendState(input.ReadString(), input.ReadString()); } } // Instanciate technique techniques[techniqueIndex] = new EffectTechnique(passes); } return(new SilverlightEffect(techniques)); }
public override void LoadResources() { if (m_Disposed == true) { m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); m_Technique = m_Effect.GetTechniqueByName("Imposter"); m_Pass_NoBlend = m_Technique.GetPassByName("NoBlend"); m_Pass_OverlayAdd = m_Technique.GetPassByName("OverlayAdd"); m_Pass_OverlaySubtract = m_Technique.GetPassByName("OverlaySubtract"); m_Pass_OverlayInvert = m_Technique.GetPassByName("OverlayInvert"); m_Pass_OverlayAlpha = m_Technique.GetPassByName("OverlayAlpha"); m_Technique_BrightPass = m_Effect.GetTechniqueByName("Imposter_BrightPass"); m_Pass_NoBlend_BrightPass = m_Technique_BrightPass.GetPassByName("NoBlend"); m_Pass_OverlayAdd_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAdd"); m_Pass_OverlaySubtract_BrightPass = m_Technique_BrightPass.GetPassByName("OverlaySubtract"); m_Pass_OverlayAlpha_BrightPass = m_Technique_BrightPass.GetPassByName("OverlayAlpha"); m_ImposterTextureResource = m_Effect.GetVariableByName("imposter").AsResource(); m_BrightPassThreshold = m_Effect.GetVariableByName("brightPassThreshold").AsScalar(); m_Layout = new InputLayout(GameEnvironment.Device, m_Pass_NoBlend.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 8, 0) }); float minX = -1f, miny = -1f, maxX = 1f, maxY = 1f; using (DataStream stream = new DataStream(4 * Marshal.SizeOf(typeof(Vertex2D)), true, true)) { stream.WriteRange(new Vertex2D[] { new Vertex2D() { Position = new Vector2(maxX, miny), TextureCoords = new Vector2(1.0f, 1.0f) }, new Vertex2D() { Position = new Vector2(minX, miny), TextureCoords = new Vector2(0.0f, 1.0f) }, new Vertex2D() { Position = new Vector2(maxX, maxY), TextureCoords = new Vector2(1.0f, 0.0f) }, new Vertex2D() { Position = new Vector2(minX, maxY), TextureCoords = new Vector2(0.0f, 0.0f) } }); stream.Position = 0; m_Vertices = new SlimDX.Direct3D11.Buffer(GameEnvironment.Device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 4 * Marshal.SizeOf(typeof(Vertex2D)), Usage = ResourceUsage.Default }); } m_VerticesBindings = new VertexBufferBinding(m_Vertices, Marshal.SizeOf(typeof(Vertex2D)), 0); m_Disposed = false; } }
/// <summary> /// 描画時に呼び出されるスプライト処理 /// </summary> /// <param name="totalTime"></param> /// <param name="elapsedTime"></param> /// <param name="render"></param> /// <param name="cbd"></param> /// <returns></returns> internal override int CallDrawingSprite( double totalTime, float elapsedTime, IMCSpriteRender render, MCCallBatchDrawing cbd ) { MCVector3 pos = new MCVector3(); MCMatrix4x4 mWVP = MCMatrix4x4.Identity; var spriteRender = (MCRenderAlphanumericSprite)render; // 頂点値を更新 spriteRender.VertexUpdate(this, out pos); // 位置の計算 if (IsBillbord) { // ビルボードである(使用できない Debug.Assert(false); } else { MCMatrix4x4 mTmp = MCMatrix4x4.Identity; // 通常スプライト mTmp.MakeRotationYawPitchRoll(m_angle.Y, m_angle.X, m_angle.Z); // 位置 mTmp.M41 += m_position.X; mTmp.M42 += m_position.Y; mTmp.M43 += m_position.Z; // スケール値 mTmp.M11 *= m_scale.X; mTmp.M21 *= m_scale.Y; mTmp.M12 *= m_scale.X; mTmp.M22 *= m_scale.Y; mTmp.M13 *= m_scale.X; mTmp.M23 *= m_scale.Y; mTmp.M14 *= m_scale.X; mTmp.M24 *= m_scale.Y; mWVP = mTmp * cbd.GetCurrentCamera().ViewProjMatrix; } cbd.SetWVP(ref mWVP); cbd.SetUniqueValue(m_uniquetValue); Sprite.Texture00.SetResource(cbd.GetDiffuseTexture()); EffectPass pass = cbd.GetEffect().GetCurrentEffectPass(); App.LayoutMgr.IASetInputLayout(pass, (int)spriteRender.GetLayoutKind()); pass.Apply(App.ImmediateContext); if (BlendState != (uint)BLENDSTATE.UNDEFINED) { App.BlendStateMgr.OMSetBlendState(BlendState); } spriteRender.Render(App.ImmediateContext, pass, this); return(0); }
/// <summary> /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> public PrimitiveQuad(GraphicsDevice graphicsDevice) { GraphicsDevice = graphicsDevice; quadEffect = ToDispose(new Effect(GraphicsDevice, effectBytecode)); quadPass = quadEffect.CurrentTechnique.Passes[0]; matrixParameter = quadEffect.Parameters["MatrixTransform"]; Transform = Matrix.Identity; sharedData = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerDevice, "Toolkit::PrimitiveQuad::VertexBuffer", () => new SharedData(GraphicsDevice)); }
private void InitializeHiDef(IGraphicsService graphicsService) { _submesh = MeshHelper.GetBox(graphicsService); _effect = graphicsService.Content.Load <Effect>("DigitalRune/Sky/Skybox"); _parameterWorldViewProjection = _effect.Parameters["WorldViewProjection"]; _parameterExposure = _effect.Parameters["Color"]; _textureParameter = _effect.Parameters["Texture"]; _passLinear = _effect.CurrentTechnique.Passes["SRgbToRgb"]; _passGamma = _effect.CurrentTechnique.Passes["SRgbToSRgb"]; }
/// <summary> /// Draw a list of Lines. /// </summary> public void Draw(List <XnaLine2d> roundLines, Matrix viewProjMatrix, float time, string techniqueName) { device.SetVertexBuffer(vb); device.Indices = ib; viewProjMatrixParameter.SetValue(viewProjMatrix); timeParameter.SetValue(time); blurThresholdParameter.SetValue(BlurThreshold); if (techniqueName == null) { effect.CurrentTechnique = effect.Techniques[0]; } else { effect.CurrentTechnique = effect.Techniques[techniqueName]; } EffectPass pass = effect.CurrentTechnique.Passes[0]; pass.Apply(); int iData = 0; int numInstancesThisDraw = 0; foreach (XnaLine2d roundLine in roundLines) { lineColorParameter.SetValue(roundLine.Color.ToVector4()); lineRadiusParameter.SetValue(roundLine.Radius); translationData[iData++] = roundLine.StartPoint.X; translationData[iData++] = roundLine.StartPoint.Y; translationData[iData++] = roundLine.Length; translationData[iData++] = roundLine.Angle; numInstancesThisDraw++; if (numInstancesThisDraw == numInstances) { instanceDataParameter.SetValue(translationData); pass.Apply(); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numPrimitivesPerInstance * numInstancesThisDraw); NumLinesDrawn += numInstancesThisDraw; numInstancesThisDraw = 0; iData = 0; } } if (numInstancesThisDraw > 0) { instanceDataParameter.SetValue(translationData); pass.Apply(); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numPrimitivesPerInstance * numInstancesThisDraw); NumLinesDrawn += numInstancesThisDraw; } }
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; }
protected virtual void SetupParamaters() { m_PassColor = _effect.CurrentTechnique.Passes["UnlitColor"]; m_PassTexture = _effect.CurrentTechnique.Passes["UnlitTexture"]; m_EPView = _effect.Parameters["View"]; m_EPProjection = _effect.Parameters["Projection"]; m_EPWorld = _effect.Parameters["World"]; m_EPTextureTilling = _effect.Parameters["TextureTilling"]; m_EPDiffuseColor = _effect.Parameters["DiffuseColor"]; m_EPMainTexture = _effect.Parameters["MainTexture"]; }
//============================================================ public void LoadFile(string fileName) { try{ var bytecode = ShaderBytecode.CompileFromFile(fileName, "fx_5_0", ShaderFlags.None, EffectFlags.None); _nativeEffect = new Effect(_device.NativeAdapter, bytecode); }catch (System.Exception ex) { throw new FFatalException(ex); } _nativeTechnique = _nativeEffect.GetTechniqueByIndex(0); _nativePass = _nativeTechnique.GetPassByIndex(0); }
public ShaderData(Effect shader, string passName) { _passName = passName; _shader = shader; if (shader == null || passName == null) { return; } _effectPass = shader.CurrentTechnique.Passes[passName]; }
private void DrawAllMeshes(EffectPass pass, bool passRenderOpaque) { _graphics.GraphicsDevice.DepthStencilState = passRenderOpaque ? DepthStencilState.Default : DepthStencilState.DepthRead; _shader.SetProjectionView(_camera.Projection); _shader.SetWorldView(_camera.World); _shader.SetModelViewIdentity(); pass.Apply(); Field.Render(_camera, _shader, pass, passRenderOpaque); }
} // end of Sphere Render() /// <summary> /// Call drawprimitive for each pass on the effect. Doesn't set any effect parameters /// or technique. /// </summary> /// <param name="effect"></param> public void DrawPrim(Effect effect) { GraphicsDevice device = BokuGame.bokuGame.GraphicsDevice; for (int indexEffectPass = 0; indexEffectPass < effect.CurrentTechnique.Passes.Count; indexEffectPass++) { EffectPass pass = effect.CurrentTechnique.Passes[indexEffectPass]; pass.Apply(); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numTriangles); } // end loop over each pass. } // end of DrawPrim()
public DeferredLightEffect() : base(Core.graphicsDevice, EffectResource.deferredLightBytes) { clearGBufferPass = Techniques["ClearGBuffer"].Passes[0]; pointLightPass = Techniques["DeferredPointLight"].Passes[0]; spotLightPass = Techniques["DeferredSpotLight"].Passes[0]; areaLightPass = Techniques["DeferredAreaLight"].Passes[0]; directionalLightPass = Techniques["DeferredDirectionalLight"].Passes[0]; finalCombinePass = Techniques["FinalCombine"].Passes[0]; cacheEffectParameters(); }
protected internal virtual EffectPass OnApply(EffectPass pass) { var handler = OnApplyCallback; if (handler != null) { pass = handler(pass); } return(pass); }
/// <summary> /// Draws the specified effect pass onto the quad. The effect pass must have a pixel shader with the signature float2:TEXCOORD. /// </summary> /// <param name="effectPass">The effect pass.</param> public void Draw(EffectPass effectPass) { ResetShaderStages(); // Apply the Effect pass effectPass.Apply(); Draw(); // Unapply this effect effectPass.UnApply(); }
/// <summary> /// A filter that allows color grading by using Look up tables /// </summary> /// <param name="graphics"></param> /// <param name="content"></param> /// <param name="shaderPath">the relative shader path needed for the content manager to load. For example "Shaders/ColorGrading/Colorgrading"</param> public ColorGradingFilter(ContentManager content, string shaderPath) { _shaderEffect = content.Load <Effect>(shaderPath); _sizeParam = _shaderEffect.Parameters["Size"]; _sizeRootParam = _shaderEffect.Parameters["SizeRoot"]; _inputTextureParam = _shaderEffect.Parameters["InputTexture"]; _lutParam = _shaderEffect.Parameters["LUT"]; _applyLUTPass = _shaderEffect.Techniques["ApplyLUT"].Passes[0]; _createLUTPass = _shaderEffect.Techniques["CreateLUT"].Passes[0]; }
/// <summary> /// Draws the specified effect pass onto the quad. The effect pass must have a pixel shader with the signature float2:TEXCOORD. /// </summary> /// <param name="effectPass">The effect pass.</param> /// <param name="fullScreenTriangle">if set to <c>true</c> to draw an optimized full screen triangle as a full screen quad.</param> public void Draw(EffectPass effectPass, bool fullScreenTriangle = false) { ResetShaderStages(); // Apply the Effect pass effectPass.Apply(); Draw(fullScreenTriangle); // Unapply this effect effectPass.UnApply(); }
//-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="FxaaFilter"/> class. /// </summary> /// <param name="graphicsService">The graphics service.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="graphicsService"/> is <see langword="null"/>. /// </exception> public FxaaFilter(IGraphicsService graphicsService) : base(graphicsService) { _effect = GraphicsService.Content.Load <Effect>("DigitalRune/PostProcessing/FxaaFilter"); _viewportSizeParameter = _effect.Parameters["ViewportSize"]; _sourceTextureParameter = _effect.Parameters["SourceTexture"]; _luminanceToAlphaPass = _effect.CurrentTechnique.Passes["LuminanceToAlpha"]; _fxaaPass = _effect.CurrentTechnique.Passes["Fxaa"]; ComputeLuminance = true; }
public DeferredLightEffect() : base(EffectResource.DeferredLightEffect) { clearGBufferPass = Techniques["ClearGBuffer"].Passes[0]; pointLightPass = Techniques["DeferredPointLight"].Passes[0]; spotLightPass = Techniques["DeferredSpotLight"].Passes[0]; areaLightPass = Techniques["DeferredAreaLight"].Passes[0]; directionalLightPass = Techniques["DeferredDirectionalLight"].Passes[0]; finalCombinePass = Techniques["FinalCombine"].Passes[0]; CacheEffectParameters(); }
public ColorGradingFilter(IRenderer renderer, SpriteBatch spriteBatch, Effect effect) { _renderer = renderer; _spriteBatch = spriteBatch; _effect = effect; _lutTextureParam = _effect.Parameters["LutTexture"]; _lutTextureWidthParam = _effect.Parameters["LutWidth"]; _lutTextureHeightParam = _effect.Parameters["LutHeight"]; _effectPass = _effect.CurrentTechnique.Passes[0]; }
/// <summary> /// A filter that allows color grading by using Look up tables /// </summary> /// <param name="graphics"></param> /// <param name="content"></param> /// <param name="shaderPath">the relative shader path needed for the content manager to load. For example "Shaders/ColorGrading/Colorgrading"</param> public ColorGradingFilter(GraphicsDevice graphics, ContentManager content, string shaderPath) { _shaderEffect = content.Load <Effect>(shaderPath); _sizeParam = _shaderEffect.Parameters["Size"]; _sizeRootParam = _shaderEffect.Parameters["SizeRoot"]; _inputTextureParam = _shaderEffect.Parameters["InputTexture"]; _lutParam = _shaderEffect.Parameters["LUT"]; _applyLUTPass = _shaderEffect.Techniques["ApplyLUT"].Passes[0]; _createLUTPass = _shaderEffect.Techniques["CreateLUT"].Passes[0]; _fsq = new FullScreenQuadRenderer(graphics); }
public static void SetRenderTexture(this KingdomShader shader, EffectPass pass, IKingdomTexture texture) { if (shader.Texture0 != texture.Texture2D) { shader.Texture0 = texture.Texture2D; switch (texture.AddressU) { case ModelTexture.TextureWrapMode.Clamp: shader.TextureRegionU = KingdomShader.DefaultTextureRegion; shader.TextureWrapModeU = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.Repeat: shader.TextureRegionU = KingdomShader.DefaultTextureRegion; shader.TextureWrapModeU = TextureWrapMode.Repeat; break; case ModelTexture.TextureWrapMode.RegionClamp: shader.TextureRegionU = texture.RegionU; shader.TextureWrapModeU = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.RegionRepeat: shader.TextureRegionU = texture.RegionU; shader.TextureWrapModeU = TextureWrapMode.Repeat; break; } switch (texture.AddressV) { case ModelTexture.TextureWrapMode.Clamp: shader.TextureRegionV = KingdomShader.DefaultTextureRegion; shader.TextureWrapModeV = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.Repeat: shader.TextureRegionV = KingdomShader.DefaultTextureRegion; shader.TextureWrapModeV = TextureWrapMode.Repeat; break; case ModelTexture.TextureWrapMode.RegionClamp: shader.TextureRegionV = texture.RegionV; shader.TextureWrapModeV = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.RegionRepeat: shader.TextureRegionV = texture.RegionV; shader.TextureWrapModeV = TextureWrapMode.Repeat; break; } pass.Apply(); } }
private void SetRenderTexture(EffectPass pass, KingdomTexture texture) { if (_shader.Texture0 != texture.Texture2D) { _shader.Texture0 = texture.Texture2D; switch (texture.ModelTexture.TextureAddressMode.AddressU) { case ModelTexture.TextureWrapMode.Clamp: _shader.TextureRegionU = KingdomShader.DefaultTextureRegion; _shader.TextureWrapModeU = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.Repeat: _shader.TextureRegionU = KingdomShader.DefaultTextureRegion; _shader.TextureWrapModeU = TextureWrapMode.Repeat; break; case ModelTexture.TextureWrapMode.RegionClamp: _shader.TextureRegionU = texture.RegionU; _shader.TextureWrapModeU = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.RegionRepeat: _shader.TextureRegionU = texture.RegionU; _shader.TextureWrapModeU = TextureWrapMode.Repeat; break; } switch (texture.ModelTexture.TextureAddressMode.AddressV) { case ModelTexture.TextureWrapMode.Clamp: _shader.TextureRegionV = KingdomShader.DefaultTextureRegion; _shader.TextureWrapModeV = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.Repeat: _shader.TextureRegionV = KingdomShader.DefaultTextureRegion; _shader.TextureWrapModeV = TextureWrapMode.Repeat; break; case ModelTexture.TextureWrapMode.RegionClamp: _shader.TextureRegionV = texture.RegionV; _shader.TextureWrapModeV = TextureWrapMode.Clamp; break; case ModelTexture.TextureWrapMode.RegionRepeat: _shader.TextureRegionV = texture.RegionV; _shader.TextureWrapModeV = TextureWrapMode.Repeat; break; } pass.Apply(); } }
/// <summary> /// スプライトを描画する /// </summary> /// <param name="immediateContext">DeviceContextポインタ。</param> /// <param name="pass">EffectPassポインタ。</param> /// <param name="drawSprite">基本描画スプライト</param> /// <return>通常、エラーが発生しなかった場合は MC_S_OK を返す。</return> public int Render(DeviceContext immediateContext, EffectPass pass, MCDrawSpriteBase drawSprite) { int[] strides = new int[] { System.Runtime.InteropServices.Marshal.SizeOf(new MC_VERTEX_PCTx()) }; int[] offsets = new int[] { 0 }; SharpDX.Direct3D11.Buffer[] vertexBuffers = new SharpDX.Direct3D11.Buffer[] { m_vertexBuffer }; immediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; immediateContext.InputAssembler.SetVertexBuffers(0, vertexBuffers, strides, offsets); immediateContext.InputAssembler.SetIndexBuffer(m_indexBuffer, SharpDX.DXGI.Format.R16_UInt, 0); immediateContext.DrawIndexed(m_drawTriangleNum * 3, 0, 0); return(0); }
public void Initialize() { _worldParam = _shader.Parameters["World"]; _worldViewProjParam = _shader.Parameters["WorldViewProj"]; _worldViewITParam = _shader.Parameters["WorldViewIT"]; _albedoMapParameter = _shader.Parameters["AlbedoMap"]; _normalMapParameter = _shader.Parameters["NormalMap"]; _frustumCornersParameter = _shader.Parameters["FrustumCorners"]; _pass1 = _shader.Techniques["Default"].Passes[0]; }
public static void SetRenderTexture(this KingdomShader shader, EffectPass pass, Texture2D texture) { if (shader.Texture0 != texture) { shader.Texture0 = texture; shader.TextureRegionU = KingdomShader.DefaultTextureRegion; shader.TextureRegionV = KingdomShader.DefaultTextureRegion; shader.TextureWrapModeU = TextureWrapMode.Clamp; shader.TextureWrapModeV = TextureWrapMode.Clamp; pass.Apply(); } }
public void Initialize() { _frustumCornersParam = _shader.Parameters["FrustumCorners"]; _cameraPositonParam = _shader.Parameters["CameraPosition"]; _depthMapParam = _shader.Parameters["DepthMap"]; _volumeTexParam = _shader.Parameters["VolumeTex"]; _volumeTexPositionParam = _shader.Parameters["VolumeTexPositionWS"]; _volumeTexSizeParam = _shader.Parameters["VolumeTexSize"]; _volumeTexResolution = _shader.Parameters["VolumeTexResolution"]; _basicPass = _shader.Techniques["Basic"].Passes[0]; }
public DebugRenderer( SlimDX.Direct3D11.Device device ) { mEffect = EffectUtil.CompileEffect( device, @"Shaders\DebugRenderer.fx" ); var positionInputElements = new[] { new InputElement( "POSITION", 0, POSITION_FORMAT, POSITION_SLOT ) }; var positionTexcoordInputElements = new[] { new InputElement( "POSITION", 0, POSITION_FORMAT, POSITION_SLOT ), new InputElement( "TEXCOORD", 0, TEXCOORD_FORMAT, TEXCOORD_SLOT ) }; EffectTechnique effectTechnique; effectTechnique = mEffect.GetTechniqueByName( "RenderWireframe" ); mRenderWireframePass = effectTechnique.GetPassByName( "RenderWireframe" ); effectTechnique = mEffect.GetTechniqueByName( "RenderSolid" ); mRenderSolidPass = effectTechnique.GetPassByName( "RenderSolid" ); effectTechnique = mEffect.GetTechniqueByName( "RenderTexture3D" ); mRenderTexture3DPass = effectTechnique.GetPassByName( "RenderTexture3D" ); effectTechnique = mEffect.GetTechniqueByName( "RenderGreyScaleTexture3D" ); mRenderGreyScaleTexture3DPass = effectTechnique.GetPassByName( "RenderGreyScaleTexture3D" ); mRenderWireframeInputLayout = new InputLayout( device, mRenderWireframePass.Description.Signature, positionInputElements ); mRenderSolidInputLayout = new InputLayout( device, mRenderSolidPass.Description.Signature, positionInputElements ); mRenderTexture3DInputLayout = new InputLayout( device, mRenderTexture3DPass.Description.Signature, positionTexcoordInputElements ); mRenderGreyScaleTexture3DInputLayout = new InputLayout( device, mRenderGreyScaleTexture3DPass.Description.Signature, positionTexcoordInputElements ); mPositionVertexBuffer = new SlimDX.Direct3D11.Buffer( device, null, NUM_VERTICES * POSITION_NUM_COMPONENTS_PER_VERTEX * POSITION_NUM_BYTES_PER_COMPONENT, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0 ); mTexCoordVertexBuffer = new SlimDX.Direct3D11.Buffer( device, null, NUM_VERTICES * TEXCOORD_NUM_COMPONENTS_PER_VERTEX * TEXCOORD_NUM_BYTES_PER_COMPONENT, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0 ); }
public bool ValidateLayout(EffectPass pass, out InputLayout layout) { layout = null; try { layout = new InputLayout(context.Device, pass.Description.Signature, this.InputLayout); return true; } catch { return false; } }
public override void LoadResources() { if (m_Disposed == true) { m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); m_Technique = m_Effect.GetTechniqueByName("BlurBilinear"); m_Pass_Gaussian = m_Technique.GetPassByName("Gaussian"); m_SourceTex = m_Effect.GetVariableByName("g_SourceTex").AsResource(); m_GWeights = m_Effect.GetVariableByName("g_GWeights").AsScalar(); //m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES; m_DataStride = Marshal.SizeOf(typeof(Vector2)) * (1 + GAUSSIAN_MAX_SAMPLES); InputElement[] IADesc = new InputElement[1 + (GAUSSIAN_MAX_SAMPLES / 2)]; IADesc[0] = new InputElement() { SemanticName = "POSITION", SemanticIndex = 0, AlignedByteOffset = 0, Slot = 0, Classification = InputClassification.PerVertexData, Format = Format.R32G32_Float }; for (int i = 1; i < 1 + (GAUSSIAN_MAX_SAMPLES / 2); i++) { IADesc[i] = new InputElement() { SemanticName = "TEXCOORD", SemanticIndex = i - 1, AlignedByteOffset = 8 + (i - 1) * 16, Slot = 0, Classification = InputClassification.PerVertexData, Format = Format.R32G32B32A32_Float }; } // Real number of "sematinc based" elements //m_ElementCount = 1 + GAUSSIAN_MAX_SAMPLES / 2; EffectPassDescription PassDesc = m_Pass_Gaussian.Description; m_Layout = new InputLayout(GameEnvironment.Device, PassDesc.Signature, IADesc); m_Disposed = false; } }
public UserInterfaceRenderCommand(Renderer renderer, Hud hud, RenderableNode rNode) : base(renderer, new UIMaterial(), new RenderableCollection(UIMaterial.ItemsDescription, new [] {rNode})) { CommandType = CommandType.UserInterfaceRenderCommand; CommandAttributes |= Graphics.CommandAttributes.MonoRendering; this.hud = hud; textMaterial = new TextMaterial(); this.rNode = rNode; this.rNode.RenderableObject.Material = Material; tNode = (TransformNode)rNode.Parent; UpdateSprites(hud.SpriteControls); textTechnique = textMaterial.EffectDescription.Technique; textPass = textTechnique.GetPassByIndex(textMaterial.EffectDescription.Pass); textLayout = new InputLayout(Game.Context.Device, textPass.Description.Signature, TextItems.Description.InputElements); }
/// <summary> /// Initializes a new instance of the <see cref="PrimitiveQuad" /> class. /// </summary> /// <param name="graphicsDevice">The graphics device.</param> public PrimitiveQuad(GraphicsDevice graphicsDevice) { GraphicsDevice = graphicsDevice; quadEffect = ToDispose(new Effect(GraphicsDevice, effectBytecode)); quadPass = quadEffect.CurrentTechnique.Passes[0]; matrixParameter = quadEffect.Parameters["MatrixTransform"]; textureCopyPass = quadEffect.CurrentTechnique.Passes[1]; textureParameter = quadEffect.Parameters["Texture"]; textureSamplerParameter = quadEffect.Parameters["TextureSampler"]; // Default LinearClamp textureSamplerParameter.SetResource(GraphicsDevice.SamplerStates.LinearClamp); Transform = Matrix.Identity; sharedData = GraphicsDevice.GetOrCreateSharedData(SharedDataType.PerDevice, "Toolkit::PrimitiveQuad::VertexBuffer", () => new SharedData(GraphicsDevice)); }
public AdjustSegmentationRenderingStrategy( SlimDX.Direct3D11.Device device, DeviceContext deviceContext, TileManager tileManager ) { mTileManager = tileManager; mDebugRenderer = new DebugRenderer( device ); mEffect = EffectUtil.CompileEffect( device, @"Shaders\AdjustRenderer2D.fx" ); var positionTexcoordInputElements = new[] { new InputElement( "POSITION", 0, POSITION_FORMAT, POSITION_SLOT ), new InputElement( "TEXCOORD", 0, TEXCOORD_FORMAT, TEXCOORD_SLOT ) }; EffectTechnique effectTechnique = mEffect.GetTechniqueByName( "TileManager2D" ); mPass = effectTechnique.GetPassByName( "TileManager2D" ); mInputLayout = new InputLayout( device, mPass.Description.Signature, positionTexcoordInputElements ); mPositionVertexBuffer = new Buffer( device, null, QUAD_NUM_VERTICES * POSITION_NUM_COMPONENTS_PER_VERTEX * POSITION_NUM_BYTES_PER_COMPONENT, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0 ); mTexCoordVertexBuffer = new Buffer( device, null, QUAD_NUM_VERTICES * TEXCOORD_NUM_COMPONENTS_PER_VERTEX * TEXCOORD_NUM_BYTES_PER_COMPONENT, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0 ); //bool result; //mTinyTextContext = new Context( device, deviceContext, Constants.MAX_NUM_TINY_TEXT_CHARACTERS, out result ); //Release.Assert( result ); mStopwatch.Start(); }
public Visualizer( D3D10Wrapper d3d, EffectManager effectManager ) { rootItemTree = new ItemTree( "root" ); this.d3d = d3d; streamState = new VisualizerStreamState(); textureVertexBuffer = new DynamicVertexBuffer( VertexPosition4fColor4f.SizeInBytes, 6 ); var stream = textureVertexBuffer.MapForWriteDiscard(); stream.Write( new Vector4f( 0, 0, 0, 1 ) ); stream.Write( new Vector4f( 0, 1, 0, 1 ) ); stream.Write( new Vector4f( 1, 0, 0, 1 ) ); stream.Write( new Vector4f( 1, 1, 0, 1 ) ); stream.Write( new Vector4f( 0, 1, 0, 1 ) ); stream.Write( new Vector4f( 0, 0, 0, 1 ) ); stream.Write( new Vector4f( 0, 1, 0, 1 ) ); stream.Write( new Vector4f( 0, 0, 0, 1 ) ); stream.Write( new Vector4f( 1, 0, 0, 1 ) ); stream.Write( new Vector4f( 1, 1, 0, 1 ) ); stream.Write( new Vector4f( 1, 1, 0, 1 ) ); stream.Write( new Vector4f( 1, 0, 0, 1 ) ); textureVertexBuffer.Unmap(); effect = effectManager[ "visualizer.fx" ]; opaquePass = effectManager[ "visualizer.fx", "renderOpaque", "p0" ]; opaquePassLayout = new InputLayout( d3d.Device, opaquePass.Description.Signature, VertexPosition4fColor4f.InputElements ); alphaPass = effectManager[ "visualizer.fx", "renderAlpha", "p0" ]; alphaPassLayout = new InputLayout( d3d.Device, alphaPass.Description.Signature, VertexPosition4fColor4f.InputElements ); additivePass = effectManager[ "visualizer.fx", "renderAdditive", "p0" ]; additivePassLayout = new InputLayout( d3d.Device, additivePass.Description.Signature, VertexPosition4fColor4f.InputElements ); opaqueTexturePass = effect.GetTechniqueByName( "renderTexOpaque" ).GetPassByName( "p0" ); opaqueTexturePassLayout = new InputLayout( d3d.Device, opaqueTexturePass.Description.Signature, VertexPosition4fTexture4f.InputElements ); alphaTexturePass = effect.GetTechniqueByName( "renderTexAlpha" ).GetPassByName( "p0" ); alphaTexturePassLayout = new InputLayout( d3d.Device, alphaTexturePass.Description.Signature, VertexPosition4fTexture4f.InputElements ); }
public void DrawBasic(DeviceContext dc, EffectPass effectPass, Matrix viewProj) { var world = World; var wit = MathF.InverseTranspose(world); var wvp = world * viewProj; Effects.BasicFX.SetWorld(world); Effects.BasicFX.SetWorldInvTranspose(wit); Effects.BasicFX.SetWorldViewProj(wvp); Effects.BasicFX.SetWorldViewProjTex(wvp * ToTexSpace); Effects.BasicFX.SetTexTransform(TexTransform); Effects.BasicFX.SetShadowTransform(world*ShadowTransform); for (int i = 0; i < Model.SubsetCount; i++) { Effects.BasicFX.SetMaterial(Model.Materials[i]); Effects.BasicFX.SetDiffuseMap(Model.DiffuseMapSRV[i]); effectPass.Apply(dc); Model.ModelMesh.Draw(dc, i); } }
public override void LoadResources() { if (m_Disposed == true) { m_Effect = m_Effect = new Effect(GameEnvironment.Device, Bytecode); // Effect.FromFile(GameEnvironment.Device, Helper.ResolvePath(m_ShaderLocation), "fx_4_0", ShaderFlags.Debug | ShaderFlags.EnableStrictness, EffectFlags.None, null, null); m_Technique = m_Effect.GetTechniqueByName("Render"); m_Pass0 = m_Technique.GetPassByName("P0"); /*m_Layout = new InputLayout(GameEnvironment.Device, m_Pass0.Description.Signature, new[] { new InputElement( "POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement( "NORMAL", 0, Format.R32G32B32_Float, 0, 12, InputClassification.PerVertexData, 0), new InputElement( "TEXCOORD", 0, Format.R32G32_Float, 0, 24, InputClassification.PerVertexData, 0), });*/ m_Layout = new InputLayout(GameEnvironment.Device, m_Pass0.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0) }); //texColorMap //texNormalMap //texDiffuseMap //texSpecularMap //m_DiffuseVariable = m_Effect.GetVariableByName("g_txDiffuse").AsResource(); m_DiffuseVariable = m_Effect.GetVariableByName("texColorMap").AsResource(); m_NormalMapVariable = m_Effect.GetVariableByName("texNormalMap").AsResource(); m_WorldVariable = m_Effect.GetVariableByName("World").AsMatrix(); m_ViewVariable = m_Effect.GetVariableByName("View").AsMatrix(); m_InvViewVariable = m_Effect.GetVariableByName("InvView").AsMatrix(); m_ProjectionVariable = m_Effect.GetVariableByName("Projection").AsMatrix(); //m_SpecularMapVariable = m_Effect.GetVariableByName("g_txEnvMap").AsResource(); m_SpecularMapVariable = m_Effect.GetVariableByName("texSpecularMap").AsResource(); m_DiffuseMapVariable = m_Effect.GetVariableByName("texDiffuseMap").AsResource(); m_EyeVariable = m_Effect.GetVariableByName("Eye").AsVector(); m_Disposed = false; } }
public void Draw(DeviceContext dc, Matrix viewProj, EffectPass pass) { var world = World; var wit = MathF.InverseTranspose(world); var wvp = world * viewProj; Effects.NormalMapFX.SetWorld(world); Effects.NormalMapFX.SetWorldInvTranspose(wit); Effects.NormalMapFX.SetWorldViewProj(wvp); Effects.NormalMapFX.SetTexTransform(Matrix.Identity); Effects.NormalMapFX.SetBoneTransforms(FinalTransforms); for (int i = 0; i < _model.SubsetCount; i++) { Effects.NormalMapFX.SetMaterial(_model.Materials[i]); Effects.NormalMapFX.SetDiffuseMap(_model.DiffuseMapSRV[i]); Effects.NormalMapFX.SetNormalMap(_model.NormalMapSRV[i]); pass.Apply(dc); _model.ModelMesh.Draw(dc, i); } }
public void ApplyPass(EffectPass pass) { pass.Apply(this.context.CurrentDeviceContext); this.ApplyCounterUAVS(); }
/// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (lightingEnabled) { // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (textureEnabled) shaderIndex += 4; if (lightingEnabled) { if (preferPerPixelLighting) shaderIndex += 24; else if (oneLight) shaderIndex += 16; else shaderIndex += 8; } shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } // Call the base class to process callbacks pass = base.OnApply(shaderPass); return pass; }
/// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/alpha material color parameter? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { diffuseColorParam.SetValue(new Vector4(diffuseColor * alpha, alpha)); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } return base.OnApply(shaderPass); }
public void SetSourceCode(string extendedSourceCode) { string shaderCode = File.ReadAllText(renderer.Directory + "\\Resources\\Teapot.fx"); try { using (ShaderBytecode bytecode = ShaderBytecode.Compile(extendedSourceCode + shaderCode, null, "fx_5_0", ShaderFlags.None, EffectFlags.None)) { effect = new Effect(renderingDevice, bytecode); } } catch (CompilationException ex) { System.Diagnostics.Debug.Write(ex.Message); return; } effectViewProjection = effect.GetVariableByName("matViewProjection").AsMatrix(); effectCameraPositionWorld = effect.GetVariableByName("cameraPositionWorld").AsVector(); technique = effect.GetTechniqueByIndex(0); pass = technique.GetPassByIndex(0); ShaderSignature signature = pass.Description.Signature; inputLayout = new InputLayout(renderingDevice, signature, new[] { new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, SlimDX.DXGI.Format.R32G32B32_Float, 12, 0) }); }
///// <summary> ///// Creates a new AlphaTestEffect by cloning parameter settings from an existing instance. ///// </summary> //protected AlphaTestEffect(AlphaTestEffect cloneSource) // : base(cloneSource) //{ // fogEnabled = cloneSource.fogEnabled; // vertexColorEnabled = cloneSource.vertexColorEnabled; // world = cloneSource.world; // view = cloneSource.view; // projection = cloneSource.projection; // diffuseColor = cloneSource.diffuseColor; // alpha = cloneSource.alpha; // fogStart = cloneSource.fogStart; // fogEnd = cloneSource.fogEnd; // alphaFunction = cloneSource.alphaFunction; // referenceAlpha = cloneSource.referenceAlpha; //} ///// <summary> ///// Creates a clone of the current AlphaTestEffect instance. ///// </summary> //public override Effect Clone() //{ // return new AlphaTestEffect(this); //} /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/alpha material color parameter? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { diffuseColorParam.SetValue(new Vector4(diffuseColor * alpha, alpha)); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } // Recompute the alpha test settings? if ((dirtyFlags & EffectDirtyFlags.AlphaTest) != 0) { var alphaTest = new Vector4(); bool eqNe = false; // Convert reference alpha from 8 bit integer to 0-1 float format. float reference = (float)referenceAlpha / 255f; // Comparison tolerance of half the 8 bit integer precision. const float threshold = 0.5f / 255f; switch (alphaFunction) { case Direct3D11.Comparison.Less: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference - threshold; alphaTest.Z = 1; alphaTest.W = -1; break; case Direct3D11.Comparison.LessEqual: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference + threshold; alphaTest.Z = 1; alphaTest.W = -1; break; case Direct3D11.Comparison.GreaterEqual: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference - threshold; alphaTest.Z = -1; alphaTest.W = 1; break; case Direct3D11.Comparison.Greater: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.X = reference + threshold; alphaTest.Z = -1; alphaTest.W = 1; break; case Direct3D11.Comparison.Equal: // Shader will evaluate: clip((abs(a - x) < Y) ? z : w) alphaTest.X = reference; alphaTest.Y = threshold; alphaTest.Z = 1; alphaTest.W = -1; eqNe = true; break; case Direct3D11.Comparison.NotEqual: // Shader will evaluate: clip((abs(a - x) < Y) ? z : w) alphaTest.X = reference; alphaTest.Y = threshold; alphaTest.Z = -1; alphaTest.W = 1; eqNe = true; break; case Direct3D11.Comparison.Never: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.Z = -1; alphaTest.W = -1; break; case Direct3D11.Comparison.Always: default: // Shader will evaluate: clip((a < x) ? z : w) alphaTest.Z = 1; alphaTest.W = 1; break; } alphaTestParam.SetValue(alphaTest); dirtyFlags &= ~EffectDirtyFlags.AlphaTest; // If we changed between less/greater vs. equal/notequal // compare modes, we must also update the shader index. if (isEqNe != eqNe) { isEqNe = eqNe; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (isEqNe) shaderIndex += 4; shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } return base.OnApply(shaderPass); }
private void LoadEffect(string shaderFileName = @"Assets\light.fx") { _effect = Effect.FromFile(_dxDevice, shaderFileName, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); _technique = _effect.GetTechniqueByName("Render"); //C++ Comparaison// technique = effect->GetTechniqueByName( "Render" ); _effectPass = _technique.GetPassByIndex(0); ShaderSignature signature = _effectPass.Description.Signature; _inputLayout = new InputLayout(_dxDevice, signature, new[] { new InputElement("POSITION", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, SlimDX.DXGI.Format.R32G32B32A32_Float, 16, 0), new InputElement("TEXCOORD", 0, SlimDX.DXGI.Format.R32G32_Float, 32, 0) }); }
private void UpdateTechnique() { this.technique = this.shaderinstance.Effect.GetTechniqueByIndex(this.techid); this.pass = this.technique.GetPassByIndex(this.passid); }
public ImageShaderPass(EffectPass pd) { this.Mips = false; this.CustomFormat = false; this.Scale = 1.0f; this.DoScale = false; this.Reference = eImageScaleReference.Previous; this.ComputeData = new ImageComputeData(pd); EffectVariable var = pd.GetAnnotationByName("format"); if (var.IsValid) { string fmt = var.AsString().GetString(); this.CustomFormat = true; this.Format = (SlimDX.DXGI.Format)Enum.Parse(typeof(SlimDX.DXGI.Format), fmt, true); } var = pd.GetAnnotationByName("mips"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.Mips = b; } var = pd.GetAnnotationByName("scale"); if (var.IsValid) { this.Scale = var.AsScalar().GetFloat(); this.DoScale = true; } var = pd.GetAnnotationByName("initial"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.Reference = b ? eImageScaleReference.Initial : eImageScaleReference.Previous; } }
public ImageComputeData(EffectPass pass) { this.Enabled = pass.ComputeShaderDescription.Variable.IsValid; this.tX = pass.GetIntAnnotation("tx", 1); this.tY = pass.GetIntAnnotation("ty", 1); this.tZ = pass.GetIntAnnotation("tz", 1); }
public ImageShaderPass(EffectPass pd) { this.Mips = false; this.CustomFormat = false; this.ScaleVector = new Vector2(1, 1); this.DoScale = false; this.Reference = eImageScaleReference.Previous; this.BlendPreset = ""; this.DepthPreset = ""; this.UseDepth = false; this.HasState = false; this.KeepTarget = false; this.Absolute = false; this.ComputeData = new ImageComputeData(pd); EffectVariable var = pd.GetAnnotationByName("format"); if (var.IsValid) { string fmt = var.AsString().GetString(); this.CustomFormat = true; this.Format = (SlimDX.DXGI.Format)Enum.Parse(typeof(SlimDX.DXGI.Format), fmt, true); } var = pd.GetAnnotationByName("mips"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.Mips = b; } var = pd.GetAnnotationByName("scale"); if (var.IsValid) { if (var.GetVariableType().Description.Class == ShaderVariableClass.Scalar) { float s = var.AsScalar().GetFloat(); this.ScaleVector = new Vector2(s, s); this.DoScale = true; } if (var.GetVariableType().Description.Class == ShaderVariableClass.Vector) { Vector4 s = var.AsVector().GetVector(); this.ScaleVector = new Vector2(s.X, s.Y); this.DoScale = true; } var = pd.GetAnnotationByName("absolute"); if (var.IsValid && var.GetVariableType().Description.Class == ShaderVariableClass.Scalar) { this.Absolute = var.AsScalar().GetFloat() > 0.5f; } } var = pd.GetAnnotationByName("initial"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.Reference = b ? eImageScaleReference.Initial : eImageScaleReference.Previous; } var = pd.GetAnnotationByName("clear"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.Clear = b; } var = pd.GetAnnotationByName("usedepth"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.UseDepth = b; } var = pd.GetAnnotationByName("keeptarget"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.KeepTarget = b; } var = pd.GetAnnotationByName("hasstate"); if (var.IsValid) { bool b = var.AsScalar().GetFloat() > 0.5f; this.HasState = b; } var = pd.GetAnnotationByName("blendpreset"); if (var.IsValid) { string blend = var.AsString().GetString(); this.BlendPreset = blend; } var = pd.GetAnnotationByName("depthpreset"); if (var.IsValid) { string depth = var.AsString().GetString(); this.DepthPreset = depth; } }