/// <summary> /// Creates the mesh manager /// </summary> /// <param name="device"></param> public XMeshManager(D3DDevice device) { this.device = device; // Create the effect //XMesh.fxo was compiled from XMesh.fx using: // "$(DXSDK_DIR)utilities\bin\x86\fxc" "$(ProjectDir)Mesh\MeshLoaders\XMesh.fx" /T fx_4_0 /Fo"$(ProjectDir)Mesh\MeshLoaders\XMesh.fxo" using (Stream effectStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "Microsoft.WindowsAPICodePack.DirectX.DirectXUtilities.XMesh.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the techniques techniqueRenderTexture = effect.GetTechniqueByName("RenderTextured"); techniqueRenderVertexColor = effect.GetTechniqueByName("RenderVertexColor"); techniqueRenderMaterialColor = effect.GetTechniqueByName("RenderMaterialColor"); // Obtain the variables brightnessVariable = effect.GetVariableByName("Brightness").AsScalar; materialColorVariable = effect.GetVariableByName("MaterialColor").AsVector; worldVariable = effect.GetVariableByName("World").AsMatrix; viewVariable = effect.GetVariableByName("View").AsMatrix; projectionVariable = effect.GetVariableByName("Projection").AsMatrix; diffuseVariable = effect.GetVariableByName("tex2D").AsShaderResource; }
private void Initialize3DTransformations(uint nWidth, uint nHeight) { worldVariable = shader.GetVariableByName("World").AsMatrix; viewVariable = shader.GetVariableByName("View").AsMatrix; projectionVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix. Vector3F eye = new Vector3F(0.0f, 2.0f, -6.0f); Vector3F at = new Vector3F(0.0f, 0.0f, 0.0f); Vector3F up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(eye, at, up); viewVariable.Matrix = viewMatrix; // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.24f, // fovy nWidth / (float)nHeight, // aspect 0.1f, // zn 100.0f // zf ); projectionVariable.Matrix = projectionMatrix; }
private void Init() { _NormalVar = GetVariableByName("g_Normal").AsShaderResource(); _MaskVar = GetVariableByName("g_Mask").AsShaderResource(); _CustomizeParameterVar = new CustomizeParameterEffectVariable(this); }
protected override bool OnAttach(IRenderHost host) { // --- attach if (!base.OnAttach(host)) { return(false); } // --- shader variables vViewport = effect.GetVariableByName("vViewport").AsVector(); bFixedSizeVariable = effect.GetVariableByName("bBillboardFixedSize").AsScalar(); // --- get geometry var geometry = geometryInternal as IBillboardText; if (geometry == null) { throw new System.Exception("Geometry must implement IBillboardText"); } // --- material // this.AttachMaterial(); this.bHasBillboardTexture = effect.GetVariableByName("bHasTexture").AsScalar(); this.billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource(); this.billboardAlphaTextureVariable = effect.GetVariableByName("billboardAlphaTexture").AsShaderResource(); this.bHasBillboardAlphaTexture = effect.GetVariableByName("bHasAlphaTexture").AsScalar(); OnCreateGeometryBuffers(); // --- set rasterstate OnRasterStateChanged(); // --- flush //Device.ImmediateContext.Flush(); return(true); }
private void Init() { _ColorMap0Var = GetVariableByName("g_ColorMap0").AsShaderResource(); _SpecularMap0Var = GetVariableByName("g_SpecularMap0").AsShaderResource(); _NormalMap0Var = GetVariableByName("g_NormalMap0").AsShaderResource(); _EnvironmentMap = GetVariableByName("g_EnvMap").AsShaderResource(); }
public void Load() { try { string path = Path.Combine(ShaderManager.ShadaresFolder, "textureEffect.fx"); using (ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile( path, "Render", "fx_5_0", ShaderFlags.EnableStrictness, EffectFlags.None)) { effect = new Effect(DeviceManager.Instance.device, effectByteCode); technique = effect.GetTechniqueByIndex(0); pass = technique.GetPassByIndex(0); inputSignature = pass.Description.Signature; } tmat = effect.GetVariableByName("gWVP").AsMatrix(); textureResourceVariable = effect.GetVariableByName("Texture").AsShaderResource(); layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private void Init() { _ColorMap0Var = GetVariableByName("g_ColorMap0").AsShaderResource(); _SpecularMap0Var = GetVariableByName("g_SpecularMap0").AsShaderResource(); _NormalMap0Var = GetVariableByName("g_NormalMap0").AsShaderResource(); _ColorVar = GetVariableByName("g_Color").AsVector(); }
public EffectMaterialVariables(Effect effect, CustomPhongMaterial material) { this.material = material; this.material.OnMaterialPropertyChanged += Material_OnMaterialPropertyChanged; this.vMaterialAmbientVariable = effect.GetVariableByName("vMaterialAmbient").AsVector(); this.vMaterialDiffuseVariable = effect.GetVariableByName("vMaterialDiffuse").AsVector(); this.vMaterialEmissiveVariable = effect.GetVariableByName("vMaterialEmissive").AsVector(); this.vMaterialSpecularVariable = effect.GetVariableByName("vMaterialSpecular").AsVector(); this.vMaterialReflectVariable = effect.GetVariableByName("vMaterialReflect").AsVector(); this.sMaterialShininessVariable = effect.GetVariableByName("sMaterialShininess").AsScalar(); this.bHasDiffuseMapVariable = effect.GetVariableByName("bHasDiffuseMap").AsScalar(); this.bHasDiffuseAlphaMapVariable = effect.GetVariableByName("bHasAlphaMap").AsScalar(); this.bHasNormalMapVariable = effect.GetVariableByName("bHasNormalMap").AsScalar(); this.bHasDisplacementMapVariable = effect.GetVariableByName("bHasDisplacementMap").AsScalar(); this.bHasShadowMapVariable = effect.GetVariableByName("bHasShadowMap").AsScalar(); this.bHasSpecularMapVariable = effect.GetVariableByName("bHasSpecularMap").AsScalar(); this.bHasEmissiveMapVariable = effect.GetVariableByName("bHasEmissiveMap").AsScalar(); this.texDiffuseMapVariable = effect.GetVariableByName("texDiffuseMap").AsShaderResource(); this.texNormalMapVariable = effect.GetVariableByName("texNormalMap").AsShaderResource(); this.texDisplacementMapVariable = effect.GetVariableByName("texDisplacementMap").AsShaderResource(); this.texShadowMapVariable = effect.GetVariableByName("texShadowMap").AsShaderResource(); this.texDiffuseAlphaMapVariable = effect.GetVariableByName("texAlphaMap").AsShaderResource(); this.texSpecularMapVariable = effect.GetVariableByName("texSpecularMap").AsShaderResource(); this.texEmissiveMapVariable = effect.GetVariableByName("texEmissiveMap").AsShaderResource(); }
private void Init() { _DiffuseVar = GetVariableByName("g_Diffuse").AsShaderResource(); _SpecularVar = GetVariableByName("g_Specular").AsShaderResource(); _NormalVar = GetVariableByName("g_Normal").AsShaderResource(); _MaskVar = GetVariableByName("g_Mask").AsShaderResource(); _TableVar = GetVariableByName("g_Table").AsShaderResource(); }
protected override void LoadShaderVariables() { _useDiffuseTextureVar = Effect.GetVariableByName("gUseDiffuseTexture").AsScalar(); _diffuseTextureVar = Effect.GetVariableByName("gDiffuseTexture").AsShaderResource(); _useNormalTextureVar = Effect.GetVariableByName("gUseNormalTexture").AsScalar(); _normalTextureVar = Effect.GetVariableByName("gNormalTexture").AsShaderResource(); _wvpMatrixVar = Effect.GetVariableBySemantic("WORLDVIEWPROJECTION").AsMatrix(); _worldMatrixVar = Effect.GetVariableBySemantic("WORLD").AsMatrix(); }
protected void SetResource <T>(EffectShaderResourceVariable variable, T value, [CallerMemberName, NotNull] string callerName = CallerHelper.EmptyName) where T : Resource { _createdResourceViews.TryGetValue(callerName, out var lastView); Utilities.Dispose(ref lastView); var newView = new ShaderResourceView(value.Device, value); _createdResourceViews[callerName] = newView; variable.SetResource(newView); }
private void Init() { _Diffuse0Var = GetVariableByName("g_Diffuse0").AsShaderResource(); _Specular0Var = GetVariableByName("g_Specular0").AsShaderResource(); _Normal0Var = GetVariableByName("g_Normal0").AsShaderResource(); _Diffuse1Var = GetVariableByName("g_Diffuse1").AsShaderResource(); _Specular1Var = GetVariableByName("g_Specular1").AsShaderResource(); _Normal1Var = GetVariableByName("g_Normal1").AsShaderResource(); }
/// <summary> /// The OnAttached /// </summary> protected override void OnAttached() { base.OnAttached(); planeParamsVar = effect.GetVariableByName("CrossPlaneParams").AsMatrix(); planeEnabledVar = effect.GetVariableByName("EnableCrossPlane").AsVector(); crossSectionColorVar = effect.GetVariableByName("CrossSectionColor").AsVector(); sectionFillTextureVar = effect.GetVariableByName("SectionFillTexture").AsShaderResource(); CreateStates(); }
/// <summary> /// /// </summary> /// <param name="val"></param> /// <param name="name"></param> protected void GetVariableShaderResource(out EffectShaderResourceVariable val, string name) { val = m_coreEffect.GetVariableByName(name).AsShaderResource(); if (!val.IsValid) { throw new Exception("変数が存在しません。エフェクトファイル[common.hlsl]内に" + name + "が存在しません。"); } }
protected override bool OnAttach(IRenderHost host) { parameters.OnAttach(this.effect); this.effectTransforms = new EffectTransformVariables(effect); effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); bHasTextureVar = effect.GetVariableByName("bHasDiffuseMap").AsScalar(); textureViewVar = effect.GetVariableByName("texDiffuseMap").AsShaderResource(); isBlendChanged = true; System.Windows.Media.CompositionTarget.Rendering += CompositionTarget_Rendering; return(true); }
public static void ApplyPreviousTexture(EffectShaderResourceVariable variable, TextureFXSettings settings) { if (settings.PreviousTexture == null) { variable.SetResource(null); } else { variable.SetResource(settings.PreviousTexture.ShaderView); } }
public virtual void OnAttach(Effect effect) { currentSimulationStateVar = effect.GetVariableByName("CurrentSimulationState").AsUnorderedAccessView(); newSimulationStateVar = effect.GetVariableByName("NewSimulationState").AsUnorderedAccessView(); simulationStateVar = effect.GetVariableByName("SimulationState").AsShaderResource(); particleSizeVar = effect.GetVariableByName("ParticleSize").AsVector(); randomVectorVar = effect.GetVariableByName("RandomVector").AsVector(); randomSeedVar = effect.GetVariableByName("RandomSeed").AsScalar(); numTextureColumnVar = effect.GetVariableByName("NumTexCol").AsScalar(); numTextureRowVar = effect.GetVariableByName("NumTexRow").AsScalar(); animateSpriteByEnergyVar = effect.GetVariableByName("AnimateByEnergyLevel").AsScalar(); }
// エフェクト関連 /// <summary> /// ID3DX11EffectShaderResourceVariable経由で、シェーダーリソースビューをセットする /// </summary> /// <param name="p"></param> /// <param name="idx">0~7 省略した場合、0</param> public void SetResource(EffectShaderResourceVariable p, int idx = 0) { if (idx > 7) { Debug.Assert(false); throw new ArgumentException(); } if (m_aTxResourceView[idx] == null) { Debug.Assert(false); throw new NotCreatedException(); } p.SetResource(m_aTxResourceView[idx]); }
public void Render(Device device, ShaderResourceView textureView) { if (_isDisposed) { throw new ObjectDisposedException(GetType().Name); } if (device == null) { return; } if (!object.ReferenceEquals(device, _cachedDevice)) { throw new InvalidOperationException(string.Format("Argument {0} and member {1} do not match!", nameof(device), nameof(_cachedDevice))); } device.InputAssembler.InputLayout = _vertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_vertices, 24, 0)); EffectTechnique technique = null; EffectPass pass = null; EffectVariable shaderResourceObj = null; EffectShaderResourceVariable shaderResource = null; try { technique = _effect.GetTechniqueByIndex(0); pass = technique.GetPassByIndex(0); shaderResourceObj = _effect.GetVariableByName("ShaderTexture"); shaderResource = shaderResourceObj.AsShaderResource(); shaderResource.SetResource(textureView); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); device.Draw(6, 0); } } finally { Disposer.RemoveAndDispose(ref shaderResource); Disposer.RemoveAndDispose(ref shaderResourceObj); Disposer.RemoveAndDispose(ref pass); Disposer.RemoveAndDispose(ref technique); } }
protected override void CompileEffectAndGetVariable(string hlslSource, string variableName) { ShaderFlags flags = ShaderFlags.None; #if DEBUG flags |= ShaderFlags.Debug | ShaderFlags.SkipOptimization; #else flags |= ShaderFlags.OptimizationLevel3; #endif using (var code = ShaderBytecode.Compile(hlslSource, "fx_5_0", flags, EffectFlags.None)) { this.fx = new Effect(device, code); } this.pass = fx.GetTechniqueByIndex(0).GetPassByIndex(0); textureVariable = fx.GetVariableByName(variableName).AsShaderResource(); }
public override void Attach(IRenderHost host) { // --- attach this.renderTechnique = Techniques.RenderBillboard; this.effect = EffectsManager.Instance.GetEffect(renderTechnique); this.renderHost = host; // --- get variables this.vertexLayout = EffectsManager.Instance.GetLayout(this.renderTechnique); this.effectTechnique = effect.GetTechniqueByName(this.renderTechnique.Name); // --- transformations this.effectTransforms = new EffectTransformVariables(this.effect); // --- shader variables this.vViewport = effect.GetVariableByName("vViewport").AsVector(); // --- get geometry var geometry = this.Geometry as BillboardText3D; if (geometry == null) { return; } // --- material // this.AttachMaterial(); billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource(); var textureBytes = BillboardText3D.Texture.ToByteArray(); billboardTextureView = ShaderResourceView.FromMemory(Device, textureBytes); billboardTextureVariable.SetResource(billboardTextureView); // -- set geometry if given vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, DefaultVertex.SizeInBytes, CreateBillboardVertexArray()); /// --- set rasterstate this.OnRasterStateChanged(this.DepthBias); /// --- flush this.Device.ImmediateContext.Flush(); }
public void Load() { try { string path = Path.Combine(ShaderManager.ShadaresFolder, "PhongTextured.fx"); using (ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile( path, "Render", "fx_5_0", ShaderFlags.EnableStrictness, EffectFlags.None)) { effect = new Effect(DeviceManager.Instance.device, effectByteCode); technique = effect.GetTechniqueByIndex(0); pass = technique.GetPassByIndex(0); inputSignature = pass.Description.Signature; } layout = new InputLayout(DeviceManager.Instance.device, inputSignature, elements); //WorldViewProjection = effect.GetVariableByName("matWorldViewProj").AsMatrix(); World = effect.GetVariableByName("World").AsMatrix(); View = effect.GetVariableByName("View").AsMatrix(); Projection = effect.GetVariableByName("Projection").AsMatrix(); //LightDir = effect.GetVariableByName("vecLightDir").AsVector(); CameraPosition = effect.GetVariableByName("CameraPosition").AsVector(); LightDirection = effect.GetVariableByName("LightDirection").AsVector(); DiffuseColor = effect.GetVariableByName("DiffuseColor").AsVector(); AmbientColor = effect.GetVariableByName("AmbientColor").AsVector(); SpecularColor = effect.GetVariableByName("SpecularColor").AsVector(); LightColor = effect.GetVariableByName("LightColor").AsVector(); SpecularPower = effect.GetVariableByName("SpecularPower").AsScalar(); TextureVariable = effect.GetVariableByName("Texture").AsShaderResource(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private void LoadEffect() { //Shader CompilationResult result = ShaderBytecode.CompileFromFile("./Resources/Shaders/ParticleRenderer.fx", "fx_4_0"); if (result.HasErrors) { DebugLog.Log(result.Message, "Error compiling shader", LogSeverity.Error); return; } _effect = new Effect(_context.Device, result.Bytecode); _technique = _effect.GetTechniqueByIndex(0); //Shader variables _viewProjVar = _effect.GetVariableBySemantic("VIEWPROJ").AsMatrix(); if (_viewProjVar == null) { DebugLog.Log("Variable with semantic 'VIEWPROJ' not found!", "Particle Emitter", LogSeverity.Error); } _viewInvVar = _effect.GetVariableBySemantic("VIEWINV").AsMatrix(); if (_viewInvVar == null) { DebugLog.Log("Variable with semantic 'VIEWINV' not found!", "Particle Emitter", LogSeverity.Error); } _textureVar = _effect.GetVariableByName("gParticleTexture").AsShaderResource(); if (_textureVar == null) { DebugLog.Log("Variable with name 'gParticleTexture' not found!", "Particle Emitter", LogSeverity.Error); } DebugLog.Log("Shader loaded", "Particle Emitter"); //Inputlayout InputElement[] vertexLayout = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, Format.R32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 1, Format.R32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_context.Device, _technique.GetPassByIndex(0).Description.Signature, vertexLayout); DebugLog.Log("Input layout created", "Particle Emitter"); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice1.CreateDeviceAndSwapChain1(host.Handle); swapChain = device.SwapChain; SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial07.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Obtain the variables worldVariable = effect.GetVariableByName("World").AsMatrix; viewVariable = effect.GetVariableByName("View").AsMatrix; projectionVariable = effect.GetVariableByName("Projection").AsMatrix; meshColorVariable = effect.GetVariableByName("vMeshColor").AsVector; diffuseVariable = effect.GetVariableByName("txDiffuse").AsShaderResource; InitVertexLayout(); InitVertexBuffer(); InitIndexBuffer(); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Load the Texture using (FileStream stream = File.OpenRead("seafloor.png")) { textureRV = TextureLoader.LoadTexture(device, stream); } InitMatrices(); diffuseVariable.Resource = textureRV; needsResizing = false; }
public override void Attach(IRenderHost host) { // --- attach renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.BillboardText]; effect = host.EffectsManager.GetEffect(renderTechnique); renderHost = host; // --- get variables vertexLayout = renderHost.EffectsManager.GetLayout(renderTechnique); effectTechnique = effect.GetTechniqueByName(renderTechnique.Name); // --- transformations effectTransforms = new EffectTransformVariables(effect); // --- shader variables vViewport = effect.GetVariableByName("vViewport").AsVector(); // --- get geometry var geometry = Geometry as IBillboardText; if (geometry == null) { return; } // -- set geometry if given vertexBuffer = Device.CreateBuffer(BindFlags.VertexBuffer, VertexSizeInBytes, CreateBillboardVertexArray()); // --- material // this.AttachMaterial(); billboardTextureVariable = effect.GetVariableByName("billboardTexture").AsShaderResource(); var textureBytes = geometry.Texture.ToByteArray(); billboardTextureView = ShaderResourceView.FromMemory(Device, textureBytes); /// --- set rasterstate OnRasterStateChanged(); /// --- flush Device.ImmediateContext.Flush(); }
private void BindTextureFor1DColorProviders() { _descriptionTextureFor1DColorProvider = new Texture1DDescription() { ArraySize = 1, BindFlags = BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.Write, Format = Format.R32G32B32A32_Float, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Dynamic, Width = 1024 }; _textureFor1DColorProvider = new Texture1D(_cachedDevice, _descriptionTextureFor1DColorProvider); _textureFor1DColorProviderView = new ShaderResourceView(_cachedDevice, _textureFor1DColorProvider); _textureFor1DColorProviderVariable = _lightingEffect.GetVariableByName("ColorGradient1DTexture"); _textureFor1DColorProviderShaderResourceVariable = _textureFor1DColorProviderVariable.AsShaderResource(); _textureFor1DColorProviderShaderResourceVariable.SetResource(_textureFor1DColorProviderView); }
public EffectMaterialVariables(Effect effect) { this.vMaterialAmbientVariable = effect.GetVariableByName("vMaterialAmbient").AsVector(); this.vMaterialDiffuseVariable = effect.GetVariableByName("vMaterialDiffuse").AsVector(); this.vMaterialEmissiveVariable = effect.GetVariableByName("vMaterialEmissive").AsVector(); this.vMaterialSpecularVariable = effect.GetVariableByName("vMaterialSpecular").AsVector(); this.vMaterialReflectVariable = effect.GetVariableByName("vMaterialReflect").AsVector(); this.sMaterialShininessVariable = effect.GetVariableByName("sMaterialShininess").AsScalar(); this.bHasDiffuseMapVariable = effect.GetVariableByName("bHasDiffuseMap").AsScalar(); this.bHasNormalMapVariable = effect.GetVariableByName("bHasNormalMap").AsScalar(); this.bHasDisplacementMapVariable = effect.GetVariableByName("bHasDisplacementMap").AsScalar(); this.bHasShadowMapVariable = effect.GetVariableByName("bHasShadowMap").AsScalar(); this.texDiffuseMapVariable = effect.GetVariableByName("texDiffuseMap").AsShaderResource(); this.texNormalMapVariable = effect.GetVariableByName("texNormalMap").AsShaderResource(); this.texDisplacementMapVariable = effect.GetVariableByName("texDisplacementMap").AsShaderResource(); this.texShadowMapVariable = effect.GetVariableByName("texShadowMap").AsShaderResource(); }
public override void Attach(IRenderHost host) { this.width = (int)(Resolution.X + 0.5f); //faktor* oneK; this.height = (int)(this.Resolution.Y + 0.5f); // faktor* oneK; base.renderTechnique = Techniques.RenderColors; base.Attach(host); if (!host.IsShadowMapEnabled) { return; } // gen shadow map this.depthBufferSM = new Texture2D(Device, new Texture2DDescription() { Format = Format.R32_Typeless, //!!!! because of depth and shader resource //Format = global::SharpDX.DXGI.Format.B8G8R8A8_UNorm, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, //!!!! CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, }); this.colorBufferSM = new Texture2D(this.Device, new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }); this.renderTargetSM = new RenderTargetView(this.Device, colorBufferSM) { }; this.depthViewSM = new DepthStencilView(Device, depthBufferSM, new DepthStencilViewDescription() { Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); this.texShadowMapView = new ShaderResourceView(Device, depthBufferSM, new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); //!!!! this.texColorMapView = new ShaderResourceView(this.Device, colorBufferSM, new ShaderResourceViewDescription() { Format = Format.B8G8R8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); this.texShadowMapVariable = effect.GetVariableByName("texShadowMap").AsShaderResource(); this.vShadowMapInfoVariable = effect.GetVariableByName("vShadowMapInfo").AsVector(); this.vShadowMapSizeVariable = effect.GetVariableByName("vShadowMapSize").AsVector(); this.shadowPassContext = new RenderContext((DPFCanvas)host, this.effect); }
/// <summary> /// Constructor /// </summary> /// <param name="variable">Variable</param> public EngineEffectVariableTexture(EffectShaderResourceVariable variable) { this.variable = variable; }
public bool Initialize() { Debug.Assert(!_initialized); #region Shaders string SpriteFX = @"Texture2D SpriteTex; SamplerState samLinear { Filter = MIN_MAG_MIP_LINEAR; AddressU = WRAP; AddressV = WRAP; }; struct VertexIn { float3 PosNdc : POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; struct VertexOut { float4 PosNdc : SV_POSITION; float2 Tex : TEXCOORD; float4 Color : COLOR; }; VertexOut VS(VertexIn vin) { VertexOut vout; vout.PosNdc = float4(vin.PosNdc, 1.0f); vout.Tex = vin.Tex; vout.Color = vin.Color; return vout; }; float4 PS(VertexOut pin) : SV_Target { return pin.Color*SpriteTex.Sample(samLinear, pin.Tex); }; technique11 SpriteTech { pass P0 { SetVertexShader( CompileShader( vs_5_0, VS() ) ); SetHullShader( NULL ); SetDomainShader( NULL ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_5_0, PS() ) ); } };"; #endregion _compiledFX = ToDispose(ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0")); { if (_compiledFX.HasErrors) { return(false); } _effect = ToDispose(new Effect(_device, _compiledFX)); { _spriteTech = ToDispose(_effect.GetTechniqueByName("SpriteTech")); _spriteMap = ToDispose(_effect.GetVariableByName("SpriteTex").AsShaderResource()); using (var pass = _spriteTech.GetPassByIndex(0)) { InputElement[] layoutDesc = { new InputElement("POSITION", 0, global::SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, global::SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, global::SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = ToDispose(new InputLayout(_device, pass.Description.Signature, layoutDesc)); } // Create Vertex Buffer BufferDescription vbd = new BufferDescription { SizeInBytes = 2048 * Marshal.SizeOf(typeof(SpriteVertex)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _VB = ToDispose(new global::SharpDX.Direct3D11.Buffer(_device, vbd)); // Create and initialise Index Buffer short[] indices = new short[3072]; for (ushort i = 0; i < 512; ++i) { indices[i * 6] = (short)(i * 4); indices[i * 6 + 1] = (short)(i * 4 + 1); indices[i * 6 + 2] = (short)(i * 4 + 2); indices[i * 6 + 3] = (short)(i * 4); indices[i * 6 + 4] = (short)(i * 4 + 2); indices[i * 6 + 5] = (short)(i * 4 + 3); } _indexBuffer = ToDispose(new SafeHGlobal(indices.Length * Marshal.SizeOf(indices[0]))); Marshal.Copy(indices, 0, _indexBuffer.DangerousGetHandle(), indices.Length); BufferDescription ibd = new BufferDescription { SizeInBytes = 3072 * Marshal.SizeOf(typeof(short)), Usage = ResourceUsage.Immutable, BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, StructureByteStride = 0 }; _IB = ToDispose(new global::SharpDX.Direct3D11.Buffer(_device, _indexBuffer.DangerousGetHandle(), ibd)); BlendStateDescription transparentDesc = new BlendStateDescription() { AlphaToCoverageEnable = false, IndependentBlendEnable = false, }; transparentDesc.RenderTarget[0].IsBlendEnabled = true; transparentDesc.RenderTarget[0].SourceBlend = BlendOption.SourceAlpha; transparentDesc.RenderTarget[0].DestinationBlend = BlendOption.InverseSourceAlpha; transparentDesc.RenderTarget[0].BlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].SourceAlphaBlend = BlendOption.One; transparentDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; transparentDesc.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; transparentDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _transparentBS = ToDispose(new BlendState(_device, transparentDesc)); } } _initialized = true; return(true); }
public 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; FarPlane = 200.0f; FieldOfView = (float)Math.PI / 4; try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 11 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; string[] sources = { "shader.fx", "grender.fx" }; using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), sources, shaderFlags)) { effect = new Effect(_device, shaderByteCode); } EffectTechnique technique = effect.GetTechniqueByName("GBufferCreate"); shadowGenPass = technique.GetPassByName("ShadowMap"); gBufferGenPass = technique.GetPassByName("GBufferGen"); debugDrawPass = technique.GetPassByName("DebugDraw"); 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 _rasterizerStateDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; noCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Back; backCullState = new RasterizerState(_device, _rasterizerStateDesc); _rasterizerStateDesc.CullMode = CullMode.Front; frontCullState = new RasterizerState(_device, _rasterizerStateDesc); _immediateContext.Rasterizer.State = CullingEnabled ? backCullState : noCullState; DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthWriteMask = DepthWriteMask.Zero; outsideLightVolumeDepthState = new DepthStencilState(_device, depthDesc); depthDesc.DepthComparison = Comparison.Greater; insideLightVolumeDepthState = 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 technique = effect.GetTechniqueByName("DeferredShader"); gBufferRenderPass = technique.GetPassByName("DeferredShader"); gBufferPostProcessPass = technique.GetPassByName("Blur"); gBufferPostProcessPass2 = technique.GetPassByName("PostProcess"); gBufferOverlayPass = technique.GetPassByName("Overlay"); lightBufferVar = effect.GetVariableByName("lightBuffer").AsShaderResource(); normalBufferVar = effect.GetVariableByName("normalBuffer").AsShaderResource(); diffuseBufferVar = effect.GetVariableByName("diffuseBuffer").AsShaderResource(); depthMapVar = effect.GetVariableByName("depthMap").AsShaderResource(); shadowLightDepthBufferVar = effect.GetVariableByName("lightDepthMap").AsShaderResource(); sunLightDirectionVar = effect.GetVariableByName("SunLightDirection").AsVector(); viewportWidthVar = effect.GetVariableByName("ViewportWidth").AsScalar(); viewportHeightVar = effect.GetVariableByName("ViewportHeight").AsScalar(); viewParametersVar = effect.GetVariableByName("ViewParameters").AsVector(); overlayViewProjectionVar = effect.GetVariableByName("OverlayViewProjection").AsMatrix(); // light.fx using (var shaderByteCode = ShaderLoader.FromResource(Assembly.GetExecutingAssembly(), "light.fx", shaderFlags)) { lightShader = new Effect(_device, shaderByteCode); } technique = lightShader.GetTechniqueByIndex(0); lightAccumulationPass = technique.GetPassByName("Light"); lightWorldVar = lightShader.GetVariableByName("World").AsMatrix(); lightPositionRadiusVar = lightShader.GetVariableByName("PositionRadius").AsVector(); lightColorVar = lightShader.GetVariableByName("Color").AsVector(); lightProjectionVar = lightShader.GetVariableByName("Projection").AsMatrix(); lightViewVar = lightShader.GetVariableByName("View").AsMatrix(); lightViewInverseVar = lightShader.GetVariableByName("ViewInverse").AsMatrix(); lightViewportWidthVar = lightShader.GetVariableByName("ViewportWidth").AsScalar(); lightViewportHeightVar = lightShader.GetVariableByName("ViewportHeight").AsScalar(); lightEyePositionVar = lightShader.GetVariableByName("EyePosition").AsVector(); lightViewParametersVar = lightShader.GetVariableByName("ViewParameters").AsVector(); InputElement[] elements = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), }; lightVolumeInputLayout = new InputLayout(Device, lightShader.GetTechniqueByIndex(0).GetPassByName("Light").Description.Signature, elements); pointLightVolumeVertices = Light.CreatePointLightVolume(out pointLightVolumeIndices); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * pointLightVolumeVertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeVertices); data.Position = 0; pointLightVolumeVertexBuffer = new Buffer(Device, data, vertexBufferDesc); } pointLightVolumeVertexBufferBinding = new VertexBufferBinding(pointLightVolumeVertexBuffer, 12, 0); BufferDescription indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(uint) * pointLightVolumeIndices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new SharpDX.DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(pointLightVolumeIndices); data.Position = 0; pointLightVolumeIndexBuffer = new Buffer(Device, data, indexBufferDesc); } lightDepthBufferVar = lightShader.GetVariableByName("depthBuffer").AsShaderResource(); lightNormalBufferVar = lightShader.GetVariableByName("normalBuffer").AsShaderResource(); lights.Add(new Light(pointLightPosition, 60, new Vector4(1, 0.95f, 0.9f, 1))); //lights.Add(new Light(pointLightPosition, 60, new Vector4(0, 0, 1, 1))); //lights.Add(new Light(new Vector3(-10, 10, 10), 30, new Vector4(1, 0, 0, 1))); //lights.Add(new Light(new Vector3(10, 5, -10), 20, new Vector4(0, 1, 0, 1))); //lights.Add(new Light(new Vector3(-10, 5, -10), 20, new Vector4(1, 0, 1, 1))); Info = new InfoText(_device, 256, 256); _meshFactory = new MeshFactory(this); CreateBuffers(); }
public override void Attach(IRenderHost host) { this.width = (int)(Resolution.X + 0.5f); //faktor* oneK; this.height = (int)(this.Resolution.Y + 0.5f); // faktor* oneK; base.renderTechnique = host.RenderTechniquesManager.RenderTechniques[DefaultRenderTechniqueNames.Colors]; base.Attach(host); if (!host.IsShadowMapEnabled) { return; } // gen shadow map this.depthBufferSM = new Texture2D(Device, new Texture2DDescription() { Format = Format.R32_Typeless, //!!!! because of depth and shader resource //Format = global::SharpDX.DXGI.Format.B8G8R8A8_UNorm, ArraySize = 1, MipLevels = 1, Width = width, Height = height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil | BindFlags.ShaderResource, //!!!! CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, }); this.colorBufferSM = new Texture2D(this.Device, new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }); this.renderTargetSM = new RenderTargetView(this.Device, colorBufferSM) { }; this.depthViewSM = new DepthStencilView(Device, depthBufferSM, new DepthStencilViewDescription() { Format = Format.D32_Float, Dimension = DepthStencilViewDimension.Texture2D, Texture2D = new DepthStencilViewDescription.Texture2DResource() { MipSlice = 0 } }); this.texShadowMapView = new ShaderResourceView(Device, depthBufferSM, new ShaderResourceViewDescription() { Format = Format.R32_Float, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); //!!!! this.texColorMapView = new ShaderResourceView(this.Device, colorBufferSM, new ShaderResourceViewDescription() { Format = Format.B8G8R8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0, } }); this.texShadowMapVariable = effect.GetVariableByName("texShadowMap").AsShaderResource(); this.vShadowMapInfoVariable = effect.GetVariableByName("vShadowMapInfo").AsVector(); this.vShadowMapSizeVariable = effect.GetVariableByName("vShadowMapSize").AsVector(); this.shadowPassContext = new RenderContext(host, this.effect); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice.CreateDeviceAndSwapChain(this.Handle, out swapChain); SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial07.fxo")) { effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream)); } // Obtain the technique technique = effect.GetTechniqueByName( "Render" ); // Obtain the variables worldVariable = effect.GetVariableByName( "World" ).AsMatrix(); viewVariable = effect.GetVariableByName( "View" ).AsMatrix(); projectionVariable = effect.GetVariableByName( "Projection" ).AsMatrix(); meshColorVariable = effect.GetVariableByName( "vMeshColor" ).AsVector(); diffuseVariable = effect.GetVariableByName( "txDiffuse" ).AsShaderResource(); InitVertexLayout(); InitVertexBuffer(); InitIndexBuffer(); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); // Load the Texture using (FileStream stream = File.OpenRead("seafloor.png")) { textureRV = TextureLoader.LoadTexture(device, stream); } InitMatrices(); diffuseVariable.SetResource(textureRV); active = true; }
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(); }
void CreateDeviceResources() { uint width = (uint) host.ActualWidth; uint height = (uint) host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); DXGIFactory dxgiFactory = DXGIFactory.CreateFactory(); SwapChainDescription swapDesc = new SwapChainDescription(); swapDesc.BufferDescription.Width = width; swapDesc.BufferDescription.Height = height; swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM; swapDesc.BufferDescription.RefreshRate.Numerator = 60; swapDesc.BufferDescription.RefreshRate.Denominator = 1; swapDesc.SampleDescription.Count = 1; swapDesc.SampleDescription.Quality = 0; swapDesc.BufferUsage = UsageOption.RenderTargetOutput; swapDesc.BufferCount = 1; swapDesc.OutputWindowHandle = host.Handle; swapDesc.Windowed = true; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntialiasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.SetState( rasterizerState ); // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.SetRenderTargets(new RenderTargetView[] {null}); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8_UNORM; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; renderDesc.Texture2D.MipSlice = 0; using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsage.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription; tex2DDescription.ArraySize = 1; tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource; tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified; tex2DDescription.Format = Format.R8G8B8A8_UNORM; tex2DDescription.Height = 4096; tex2DDescription.Width = 512; tex2DDescription.MipLevels = 1; tex2DDescription.MiscFlags = 0; tex2DDescription.SampleDescription.Count = 1; tex2DDescription.SampleDescription.Quality = 0; tex2DDescription.Usage = Usage.Default; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GetDXGISurface()) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix(); viewMatrixVariable = shader.GetVariableByName("View").AsMatrix(); projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix(); diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource(); // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.SetInputLayout( vertexLayout ); IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindFlags = BindFlag.VertexBuffer; bd.CpuAccessFlags = CpuAccessFlag.Unspecified; bd.MiscFlags = ResourceMiscFlag.Undefined; SubresourceData InitData = new SubresourceData() { SysMem = verticesDataPtr }; vertexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] {vertexBuffer}, new uint[] {stride}, new uint[] {offset} ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindFlags = BindFlag.IndexBuffer; bd.CpuAccessFlags = 0; bd.MiscFlags = 0; InitData.SysMem = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList); // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float) Math.PI*0.1f, width/(float) height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(Colors.Yellow)), new GradientStop(1.0f, new ColorF(Colors.Black)) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.Gamma_22, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
/// <summary> /// Create Direct3D device and swap chain /// </summary> protected void InitDevice() { device = D3DDevice1.CreateDeviceAndSwapChain1(directControl.Handle); swapChain = device.SwapChain; SetViews(); // Create the effect using (FileStream effectStream = File.OpenRead("Tutorial07.fxo")) { effect = device.CreateEffectFromCompiledBinary(effectStream); } // Obtain the technique technique = effect.GetTechniqueByName("Render"); // Obtain the variables worldVariable = effect.GetVariableByName("World").AsMatrix; viewVariable = effect.GetVariableByName("View").AsMatrix; projectionVariable = effect.GetVariableByName("Projection").AsMatrix; meshColorVariable = effect.GetVariableByName("vMeshColor").AsVector; diffuseVariable = effect.GetVariableByName("txDiffuse").AsShaderResource; InitVertexLayout(); InitVertexBuffer(); InitIndexBuffer(); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Load the Texture textureRV = TextureLoader.LoadTexture(device, "seafloor.png"); InitMatrices(); diffuseVariable.Resource = textureRV; needsResizing = false; }
private void Initialize3DTransformations(uint nWidth, uint nHeight) { worldVariable = shader.GetVariableByName("World").AsMatrix; viewVariable = shader.GetVariableByName("View").AsMatrix; projectionVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix. Vector3F eye = new Vector3F(0.0f, 2.0f, -6.0f); Vector3F at = new Vector3F(0.0f, 0.0f, 0.0f); Vector3F up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(eye, at, up); viewVariable.Matrix = viewMatrix; // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.24f, // fovy nWidth / (float)nHeight, // aspect 0.1f, // zn 100.0f // zf ); projectionVariable.Matrix = projectionMatrix; }