Sign in to follow this  
Barguast

DX11 [SlimDX / D3D11] - Loading effects

Recommended Posts

Barguast    181
Today has been a painful introduction to Direct3D 11 for me. I have successfully got a device initiated and displaying a blank screen (no geometry). I'm now trying to load and apply an effect to get some geometry showing. Unfortunately, the loading and usage of an effect is tripping me up. I think the problem is down to the fact that I'm targetting 'FeatureLevel.Level_9_1' but I'm not sure. Here is my fx file, as simple as can be:
struct VS_IN
{
	float4 pos : POSITION;
};

struct PS_IN
{
	float4 pos : SV_POSITION;
};

PS_IN vs_main(VS_IN input)
{
	PS_IN output = (PS_IN)0;
	output.pos = input.pos;
	return output;
}

float4 ps_main(PS_IN input) : SV_Target
{
	return float4(1, 0, 0, 1);
}

technique Render
{
	pass P0
	{
		SetVertexShader(CompileShader(vs_2_0, vs_main()));
		SetPixelShader (CompileShader(ps_2_0, ps_main()));
	}
}


Note that it's simple vertex / pixel shader. And this is me trying to load the effect:
ShaderBytecode effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "Render", "fx_5_0", /*"vs_4_0_level_9_1", */ShaderFlags.EnableStrictness, EffectFlags.None);
Effect effect = new Effect(this.device, this.effectByteCode, EffectFlags.None);


The loads succeeds (although I'm unsure if it's 'safe' to use the "fx_5_0" profile when targetting Direct3D 9, and vertex / pixel shaders 2.0)? The 'vs_4_0_level_9_1' comment was an alternative profile that I tried, with no success. The problem occurs when I try to use the effect:
EffectTechnique tech = effect.GetTechniqueByIndex(0);
                    EffectPass pass = tech.GetPassByIndex(0);

                    InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
                    {
                        new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
                    });


GetTechniqueByIndex fails with 'ID3DX11Effect::GetTechniqueByIndex: Invalid technique index (0)', which doesn't cause SlimDX to except until the InputLayout instance is created. I've tried the same with the following:
EffectTechnique tech = effect.GetTechniqueByName("Render");
                    EffectPass pass = tech.GetPassByIndex(0);

                    InputLayout input = new InputLayout(this.device, pass.Description.Signature, new InputElement[]
                    {
                        new InputElement("POSITION0", 0, Format.R32G32B32_Float, 0, 0)
                    });


But then the GetTechniqueByName method excepts with 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' I'm not sure where I'm going wrong - if my shader code is wrong, if it's compiled incorrectly for Direct3D 9, etc. Hopefully someone can help me? Thanks.

Share this post


Link to post
Share on other sites
Barguast    181
I tried 'fx_2_0', and got the exception '[7860] Effects11: Effect version is unrecognized. This runtime supports fx_5_0 to fx_5_0.'. It may just be a weird error message, but that suggests to me that ONLY the fx_5_0 is supported.

I also tried 'vs_4_0_level_9_1', but I get the exception 'error X3501: 'Render': entrypoint not found'. I'm not sure what an entry point in terms of an effect file, but I assumed 'Render' would be it..!

Share this post


Link to post
Share on other sites
Barguast    181
As far as I can tell, neither is valid - if it's null I get the exception:

"String reference not set to an instance of a String.
Parameter name: s"

If set it to be empty string, I get another exception

"Index was outside the bounds of the array."

I thought I couldn't use 'technique10' when using the 'FeatureLevel.Level_9_1' feature level?

Thanks for your help so far.

Share this post


Link to post
Share on other sites
jpetrie    13102
Dunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.

Share this post


Link to post
Share on other sites
Barguast    181
I did wonder why there weren't any. I also wondered why Effect.FromFile was missing - is the effects framework unfinished in SlimDX perhaps?

In fact, should I even be loading effect files with ShaderBytecode.CompileFromFile I wonder? It looks to me like a shader compilation function, and not an effects one...

Share this post


Link to post
Share on other sites
jpetrie    13102
Effects11 (the underlying native library) is rather different than the previous versions of the effect framework. You're supposed to compile the effect to bytecode and load that, there isn't a 'from file' method any longer.

Share this post


Link to post
Share on other sites
Barguast    181
I got a bit further! Not necessarily in the right direction. I made file a plain vertex shader (no techniques, passes, etc).
struct VS_IN
{
float4 pos : POSITION;
};

struct PS_IN
{
float4 pos : SV_POSITION;
};

PS_IN vs_main(VS_IN input)
{
PS_IN output = (PS_IN)0;
output.pos = input.pos;
return output;
}


And tried to load and it as follows:

effectByteCode = ShaderBytecode.CompileFromFile("Default2.fx", "vs_main", "vs_4_0_level_9_1", ShaderFlags.None, EffectFlags.None);
vertexShader = new VertexShader(this.device, effectByteCode);

[...]

InputLayout input = new InputLayout(this.device, ShaderSignature.GetInputSignature(this.effectByteCode), new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0)
});

context.VertexShader.Set(this.vertexShader);


The shader appears to be loaded, but falls on creating the InputLayout with this error:

'[7560] D3D11: ERROR: ID3D11Device::CreateInputLayout: Input Signature in bytecode could not be parsed. Data may be corrupt or in an unrecognizable format. [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE ]'

Share this post


Link to post
Share on other sites
DieterVW    724
You have to use technique11, the others will not work when using Effects11 API.

You have to compile with "fx_5_0", nothing else will work when using Effects11 API.

In your effect file, you have to compile for your target: which is 9_1, not 2_0 when using feature levels.



SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));


Share this post


Link to post
Share on other sites
Barguast    181
A-ha! That seems to have done the trick.

I'm not getting any output but the effect is loaded. I'm getting another message in DebugView:

[7808] D3D11: WARNING: ID3D11DeviceContext::Draw: Vertex Buffer at the input vertex slot 0 is not big enough for what the Draw*() call expects to traverse. This is OK, as reading off the end of the Buffer is defined to return 0. However the developer probably did not intend to make use of this behavior. [ EXECUTION WARNING #356: DEVICE_DRAW_VERTEX_BUFFER_TOO_SMALL ]

But I think I might have an idea what the problem is.


Thank you both.

@ DieterVW - So this effect, despite having a 'technique11' will work on the Level_9_1 feature level? And will render correctly to Direct3D9 hardware? The 'vs_4_0_level_9_1' string suggests to me that it'll only work on Direct3D9 hardware that supports Vertex Shaders 4.0. Is that right?

Thanks again. :D

Share this post


Link to post
Share on other sites
Mike.Popoloski    3258
There's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.

Share this post


Link to post
Share on other sites
adt7    751
Quote:
Original post by Mike.Popoloski
There's a problem with the Get*Signature methods of the ShaderSignature class. The source in the SVN repository has an additional constructor for InputLayout that takes a full shader bytecode, but we're still working on fixing the shader signature methods.


The InputLayout methods work when using effect.GetTechniqueByIndex(...).GetPassByIndex(...).Description.Signature, but not when using a ShaderSignature obtained using the ShaderSignature.Get*Signature() methods currently, although the fix in the SVN solves that.

As for feature levels, I've never managed to get the effects system to work properly with anything under Level_9_3. Is there any reason you can't target this instead of 9_1? I could give you some pointers then.

Quote:
Original post by jpetrie
Dunno. I'm just guessing. I hadn't ever been able to get effects in D3D11 working properly, although I didn't try very hard. It's the main reason we don't have D3D11 samples in SlimDX yet.


It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.

Share this post


Link to post
Share on other sites
DieterVW    724
The feature level targets are a bit confusing, but here is what happens. When running a feature 10Level9, the entire runtime will start making only DX9 DDI driver calls. So you are constrained to using features that exist only in DX9 and having to use shaders that are compiled to be used with the DX10 runtime, but target the DX9 driver.

These 10Level9 shaders contain 2 shader blobs, one is 9_x and one is 4_0, depending on the device, the runtime will make use of the correct shader blob for you.

Share this post


Link to post
Share on other sites
Barguast    181
Quote:
Original post by adt7
It's not as easy as it could be, but it does work with the Feb release. If you want a hand with producing samples I can provide code.


I'd find that very helpful.

This my entire test project (which still isn't work properly - it should render a triangle using WARP... but doesn't). I at least got around the effect loading problems though..!

If anyone can spot the problem, please let me know. I'll persevere and update if I solve it.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SlimDX.Direct3D11;
using SlimDX.DXGI;
using SlimDX;

using Device = SlimDX.Direct3D11.Device;
using Buffer = SlimDX.Direct3D11.Buffer;
using System.Runtime.InteropServices;

namespace TestDirect3D11
{
public partial class Form1 : Form
{
private Device device;
private SwapChain swapChain;
private RenderTargetView renderTargetView;
private Texture2D texture;
private Buffer vertexBuffer;

private ShaderBytecode effectByteCode;
private Effect defaultEffect;

public Form1()
{
InitializeComponent();

// Create the swap chain description
SwapChainDescription swapChainDescription = new SwapChainDescription()
{
BufferCount = 2,
IsWindowed = true,
Flags = SwapChainFlags.None,
ModeDescription = new ModeDescription(this.Width, this.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
OutputHandle = this.Handle,
SampleDescription = new SampleDescription(1, 0),
SwapEffect = SwapEffect.Discard,
Usage = Usage.RenderTargetOutput
};

// Create the Direct3D11 device, using the WARP driver, and targetting Direct3D 9
Device.CreateWithSwapChain(null, DriverType.Warp, DeviceCreationFlags.None, new FeatureLevel[] { FeatureLevel.Level_9_1 }, swapChainDescription, out this.device, out this.swapChain);
this.ResizeBackBuffer();

// Load the vertex buffer
Vector4[] vertices =
{
new Vector4(50F, 0F, 1F, 1F),
new Vector4(100F, 100F, 1F, 1F),
new Vector4(0F, 100F, 1F, 1F)
};

int stride = Marshal.SizeOf(typeof(Vector4));
int length = stride * vertices.Length;

using (DataStream vertexDataStream = new DataStream(vertices, true, true))
{
this.vertexBuffer = new Buffer(this.device, vertexDataStream,
new BufferDescription(length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, stride));
}

string errors;
this.effectByteCode = ShaderBytecode.CompileFromFile("Default.fx", "vs_main", "fx_5_0", ShaderFlags.None, EffectFlags.None, null, null, out errors);
this.defaultEffect = new Effect(this.device, this.effectByteCode, EffectFlags.None);
}

private void ResizeBackBuffer()
{
// Dispose of the previous render target view
if (this.renderTargetView != null)
this.renderTargetView.Dispose();

// Resize the swap chain buffers
this.swapChain.ResizeBuffers(2, this.Width, this.Height, Format.R8G8B8A8_UNorm, SwapChainFlags.None);

// Create the new render target view
using (Texture2D backBuffer = Texture2D.FromSwapChain<Texture2D>(this.swapChain, 0))
{
this.renderTargetView = new RenderTargetView(this.device, backBuffer);
}
}

protected override void OnPaint(PaintEventArgs e)
{
if (swapChain != null)
{
try
{
DeviceContext context = this.device.ImmediateContext;

context.ClearRenderTargetView(this.renderTargetView, new Color4(0F, 0F, 0F));

EffectTechnique tech = this.defaultEffect.GetTechniqueByIndex(0);
EffectPass pass = tech.GetPassByIndex(0);

ShaderSignature shaderSignature = pass.Description.Signature;
InputLayout input = new InputLayout(this.device, shaderSignature, new InputElement[]
{
new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
});

this.defaultEffect.GetVariableByName("worldViewProjection").AsMatrix().SetMatrix(Matrix.OrthoOffCenterLH(0F, this.Width, this.Height, 0F, 0F, 100F));

context.InputAssembler.InputLayout = input;
context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.vertexBuffer, Marshal.SizeOf(typeof(Vector4)), 0));
for (int i = 0; i < tech.Description.PassCount; ++i)
{
tech.GetPassByIndex(i).Apply(context);
context.Draw(3, 0);
}

this.swapChain.Present(0, PresentFlags.None);
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}

base.OnPaint(e);
}

protected override void OnResize(EventArgs e)
{
this.ResizeBackBuffer();
base.OnResize(e);
}

protected override void OnPaintBackground(PaintEventArgs e)
{
//base.OnPaintBackground(e);
}

protected override void OnFormClosed(FormClosedEventArgs e)
{
// Dispose of the Direct3D resources
this.effectByteCode.Dispose();
this.defaultEffect.Dispose();
this.vertexBuffer.Dispose();
this.renderTargetView.Dispose();
this.swapChain.Dispose();
this.device.Dispose();

base.OnFormClosed(e);
}
}
}






Default.fx

float4x4 worldViewProjection;

struct VS_IN
{
float4 Position : POSITION0;
};

struct PS_IN
{
float4 Position : SV_POSITION;
};


// -------------
// Vertex Shader
// -------------
PS_IN vs_main(VS_IN input) : SV_POSITION
{
PS_IN output;
output.Position = mul(input.Position, worldViewProjection);
return output;
}

// ------------
// Pixel Shader
// ------------
float4 ps_main(PS_IN input) : SV_TARGET
{
return float4(1, 1, 1, 1);
}


// ----------
// Techniques
// ----------
technique11 Render
{
pass Pass_0
{
SetVertexShader(CompileShader(vs_4_0_level_9_1, vs_main()));
SetPixelShader(CompileShader(ps_4_0_level_9_1, ps_main()));
}
}


I know it doesn't clean things up and is generally horribly written. I'll tidy it up once it works! :p

Share this post


Link to post
Share on other sites
Mike.Popoloski    3258
First of all, don't use OnPaint as a real-time rendering mechanism. It's not designed for that. Reasoning.

As for your problem, you're missing two crucial steps:
1. You need to actual set your render target to the output merger.
2. You need to set a viewport.

For example:

device.ImmediateContext.OutputMerger.SetTargets(renderTargetView);
device.ImmediateContext.Rasterizer.SetViewports(new Viewport(0, 0, ClientSize.Width, ClientSize.Height));

Share this post


Link to post
Share on other sites
Barguast    181
Hurray! It works! Thanks for the tip about using OnPaint, this was only a test app, but it's good information to know as it probably would've crept into an actual project.

EDIT: How do I stop the MessagePump? My application excepts when the form is closed when I use it. Specifically:

ObjectDisposedException at Application.Run(new Form1());

Cannot access a disposed object.
Object name: 'Form1'.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By gsc
      Hi! I am trying to implement simple SSAO postprocess. The main source of my knowledge on this topic is that awesome tutorial.
      But unfortunately something doesn't work... And after a few long hours I need some help. Here is my hlsl shader:
      float3 randVec = _noise * 2.0f - 1.0f; // noise: vec: {[0;1], [0;1], 0} float3 tangent = normalize(randVec - normalVS * dot(randVec, normalVS)); float3 bitangent = cross(tangent, normalVS); float3x3 TBN = float3x3(tangent, bitangent, normalVS); float occlusion = 0.0; for (int i = 0; i < kernelSize; ++i) { float3 samplePos = samples[i].xyz; // samples: {[-1;1], [-1;1], [0;1]} samplePos = mul(samplePos, TBN); samplePos = positionVS.xyz + samplePos * ssaoRadius; float4 offset = float4(samplePos, 1.0f); offset = mul(offset, projectionMatrix); offset.xy /= offset.w; offset.y = -offset.y; offset.xy = offset.xy * 0.5f + 0.5f; float sampleDepth = tex_4.Sample(textureSampler, offset.xy).a; sampleDepth = vsPosFromDepth(sampleDepth, offset.xy).z; const float threshold = 0.025f; float rangeCheck = abs(positionVS.z - sampleDepth) < ssaoRadius ? 1.0 : 0.0; occlusion += (sampleDepth <= samplePos.z + threshold ? 1.0 : 0.0) * rangeCheck; } occlusion = saturate(1 - (occlusion / kernelSize)); And current result: http://imgur.com/UX2X1fc
      I will really appreciate for any advice!
    • By isu diss
       I'm trying to code Rayleigh part of Nishita's model (Display Method of the Sky Color Taking into Account Multiple Scattering). I get black screen no colors. Can anyone find the issue for me?
       
      #define InnerRadius 6320000 #define OutterRadius 6420000 #define PI 3.141592653 #define Isteps 20 #define Ksteps 10 static float3 RayleighCoeffs = float3(6.55e-6, 1.73e-5, 2.30e-5); RWTexture2D<float4> SkyColors : register (u0); cbuffer CSCONSTANTBUF : register( b0 ) { float fHeight; float3 vSunDir; } float Density(float Height) { return exp(-Height/8340); } float RaySphereIntersection(float3 RayOrigin, float3 RayDirection, float3 SphereOrigin, float Radius) { float t1, t0; float3 L = SphereOrigin - RayOrigin; float tCA = dot(L, RayDirection); if (tCA < 0) return -1; float lenL = length(L); float D2 = (lenL*lenL) - (tCA*tCA); float Radius2 = (Radius*Radius); if (D2<=Radius2) { float tHC = sqrt(Radius2 - D2); t0 = tCA-tHC; t1 = tCA+tHC; } else return -1; return t1; } float RayleighPhaseFunction(float cosTheta) { return ((3/(16*PI))*(1+cosTheta*cosTheta)); } float OpticalDepth(float3 StartPosition, float3 EndPosition) { float3 Direction = normalize(EndPosition - StartPosition); float RayLength = RaySphereIntersection(StartPosition, Direction, float3(0, 0, 0), OutterRadius); float SampleLength = RayLength / Isteps; float3 tmpPos = StartPosition + 0.5 * SampleLength * Direction; float tmp; for (int i=0; i<Isteps; i++) { tmp += Density(length(tmpPos)-InnerRadius); tmpPos += SampleLength * Direction; } return tmp*SampleLength; } static float fExposure = -2; float3 HDR( float3 LDR) { return 1.0f - exp( fExposure * LDR ); } [numthreads(32, 32, 1)] //disptach 8, 8, 1 it's 256 by 256 image void ComputeSky(uint3 DTID : SV_DispatchThreadID) { float X = ((2 * DTID.x) / 255) - 1; float Y = 1 - ((2 * DTID.y) / 255); float r = sqrt(((X*X)+(Y*Y))); float Theta = r * (PI); float Phi = atan2(Y, X); static float3 Eye = float3(0, 10, 0); float ViewOD = 0, SunOD = 0, tmpDensity = 0; float3 Attenuation = 0, tmp = 0, Irgb = 0; //if (r<=1) { float3 ViewDir = normalize(float3(sin(Theta)*cos(Phi), cos(Theta),sin(Theta)*sin(Phi) )); float ViewRayLength = RaySphereIntersection(Eye, ViewDir, float3(0, 0, 0), OutterRadius); float SampleLength = ViewRayLength / Ksteps; //vSunDir = normalize(vSunDir); float cosTheta = dot(normalize(vSunDir), ViewDir); float3 tmpPos = Eye + 0.5 * SampleLength * ViewDir; for(int k=0; k<Ksteps; k++) { float SunRayLength = RaySphereIntersection(tmpPos, vSunDir, float3(0, 0, 0), OutterRadius); float3 TopAtmosphere = tmpPos + SunRayLength*vSunDir; ViewOD = OpticalDepth(Eye, tmpPos); SunOD = OpticalDepth(tmpPos, TopAtmosphere); tmpDensity = Density(length(tmpPos)-InnerRadius); Attenuation = exp(-RayleighCoeffs*(ViewOD+SunOD)); tmp += tmpDensity*Attenuation; tmpPos += SampleLength * ViewDir; } Irgb = RayleighCoeffs*RayleighPhaseFunction(cosTheta)*tmp*SampleLength; SkyColors[DTID.xy] = float4(Irgb, 1); } }  
    • By amadeus12
      I made my obj parser
      and It also calculate tagent space for normalmap.
      it seems calculation is wrong..
      any good suggestion for this?
      I can't upload my pics so I link my question.
      https://gamedev.stackexchange.com/questions/147199/how-to-debug-calculating-tangent-space
      and I uploaded my code here


      ObjLoader.cpp
      ObjLoader.h
    • By Alessandro Pozzer
      Hi guys, 

      I dont know if this is the right section, but I did not know where to post this. 
      I am implementing a day night cycle on my game engine and I was wondering if there was a nice way to interpolate properly between warm colors, such as orange (sunset) and dark blue (night) color. I am using HSL format.
      Thank  you.
    • By thefoxbard
      I am aiming to learn Windows Forms with the purpose of creating some game-related tools, but since I know absolutely nothing about Windows Forms yet, I wonder:
      Is it possible to render a Direct3D 11 viewport inside a Windows Form Application? I see a lot of game editors that have a region of the window reserved for displaying and manipulating a 3D or 2D scene. That's what I am aiming for.
      Otherwise, would you suggest another library to create a GUI for game-related tools?
       
      EDIT:
      I've found a tutorial here in gamedev that shows a solution:
      Though it's for D3D9, I'm not sure if it would work for D3D11?
       
  • Popular Now