public void Test() { var device = GraphicsDevice.New(); // Compile a toolkit effect from a file var result = EffectCompiler.CompileFromFile("toto.fx"); // Check that we don't have any errors Assert.False(result.HasErrors); var bytecode = result.EffectData; var effect = new Effect(device, bytecode); var tex1 = TextureCube.New(device, 64, PixelFormat.R8.UNorm); var samplerState = device.SamplerStates.PointWrap; effect.Parameters["SkyBoxTexture"].SetResource(tex1); effect.Parameters["SkyBoxSampler"].SetResource(samplerState); effect.Techniques[0].Passes[0].Apply(); Console.WriteLine(effect.Parameters.Count); effect.Dispose(); device.Dispose(); }
public void Init() { if (DXEffect != null) DXEffect.Dispose(); CompilationResult cr = null; EffectFlags EFFECT_FLAGS = EffectFlags.None; #if DEBUG ShaderFlags SHADER_FLAGS = ShaderFlags.Debug; #else ShaderFlags SHADER_FLAGS = ShaderFlags.OptimizationLevel3; #endif try { _isValid = true; cr = ShaderBytecode.CompileFromFile(ShaderFullFilename, "fx_5_0", SHADER_FLAGS, EFFECT_FLAGS, null, new IncludeFX(Program.DXConfig.ShadersIncludePath)); DXEffect = new Effect(Program.Renderer.DXDevice, cr.Bytecode); cr.Bytecode.Dispose(); Dirty = false; } catch (Exception e) { _isValid = false; string text = "Compilation failed for shader: " + ShaderFullFilename + "\n" + e.Message; if (MessageBox.Show(text, "Shader compiler", MessageBoxButtons.RetryCancel) == DialogResult.Retry) { Init(); } } }
public void TestCompiler() { var device = GraphicsDevice.New(); // Compile a toolkit effect from a file var result = new EffectCompiler().CompileFromFile("TestEffectTextureArray.fx"); // Check that we don't have any errors Assert.False(result.HasErrors); var bytecode = result.EffectData; var effect = new Effect(device, bytecode); var tex1 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var tex2 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var tex3 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var samplerState = device.SamplerStates.PointWrap; effect.Parameters["testTextureArray"].SetResource(0, tex1); effect.Parameters["testTextureArray"].SetResource(1, tex2); effect.Parameters["testTextureArray"].SetResource(2, tex3); //effect.Parameters["World"].SetValue(Vector3.Zero); //effect.Parameters["Tata"].SetResource(texture); effect.Techniques[0].Passes[0].Apply(); effect.Techniques[0].Passes[1].Apply(); Console.WriteLine(effect.Parameters.Count); effect.Dispose(); device.Dispose(); }
public RenderTechnique(string name, Effect effect, InputLayout layout) { this.Name = name; this.Device = effect.Device; this.Effect = effect; this.EffectTechnique = effect.GetTechniqueByName(this.Name); this.InputLayout = layout; }
public Effect CreateEffectFromFile(string fileName) { using (var byteCode = LoadByteCodeFromFile(ShaderType.Effect, fileName)) { var effect = new Effect(Device, byteCode); return effect; } }
public void TestCompiler() { var device = GraphicsDevice.New(); // Compile a toolkit effect from a file var result = new EffectCompiler().CompileFromFile("TestEffect.fx"); // Check that we don't have any errors Assert.False(result.HasErrors); var bytecode = result.EffectData; // Check that we have a single effect compiled in this archive. Assert.AreEqual(bytecode.Effects.Count, 1); // Check that the name of this effect is the file name Assert.AreEqual(bytecode.Effects[0].Name, "TestEffect"); // We have 3 shaders compiled: VS, VS2, PS Assert.AreEqual(bytecode.Shaders.Count, 3); // Check that this is the profile 10.0 Assert.AreEqual(bytecode.Shaders[0].Level, FeatureLevel.Level_10_0); // Create a EffectData pool from a single EffectData var effectGroup = EffectPool.New(device); //var effect = effectGroup.New<BasicEffect>(); var effect = new Effect(device, bytecode, effectGroup); //Texture2D tex : register(t0); //Texture2D tex1 : register(t2); //Texture2D tex2 : register(t3); //Texture2D tex3 : register(t10); //SamplerState samp; var tex = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var tex1 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var tex2 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var tex3 = Texture2D.New(device, 256, 256, PixelFormat.R8.UNorm); var samplerState = device.SamplerStates.PointWrap; effect.Parameters["tex"].SetResource(tex); effect.Parameters["tex1"].SetResource(tex1); effect.Parameters["tex2"].SetResource(tex2); effect.Parameters["tex3"].SetResource(tex3); effect.Parameters["worldViewProj"].SetValue(Matrix.Identity); effect.Parameters["samp"].SetResource(samplerState); //effect.Parameters["World"].SetValue(Vector3.Zero); //effect.Parameters["Tata"].SetResource(texture); effect.Techniques[0].Passes[0].Apply(); Console.WriteLine(effect.Parameters.Count); effect.Dispose(); device.Dispose(); }
internal void Compile() { var fileName = _fileName; var device = _device; if (!File.Exists(fileName)) { throw new FileNotFoundException($"Effect file '{fileName}' is not found.", fileName); } var fileInfo = new FileInfo(fileName); using (var includeProcessor = new IncludeProcessor(fileInfo.DirectoryName)) { // SharpDX 当前(2016-04-04)使用的D3DCompiler版本为47,fx目标只支持 fx_5_0。 // 详见 https://msdn.microsoft.com/en-us/library/windows/desktop/hh446869.aspx 和 https://msdn.microsoft.com/en-us/library/windows/desktop/jj215820.aspx。 // 例如,使用 fx_4_0 的配置进行编译和设置,语法上没问题,但是无法创建 Effect。也就是说,D3DCompile2 是支持 fx_4_0 编译的,但是编译状态中有过时选项警告, // 导致能生成 bytecode(Bytecode 属性非空),但是 Effect 创建时抛出异常。 using (var compilationResult = ShaderBytecode.CompileFromFile(fileName, null, "fx_5_0", ShaderFlags.None, EffectFlags.None, null, includeProcessor)) { _dxEffect = new Effect(device, compilationResult.Bytecode, EffectFlags.None, fileName); } } }
public InstancedGeometricPrimitive(GraphicsDevice d) { device = d; byte[] bCode = ShaderBytecode.Compile(Resources.BasicEffect, "fx_5_0"); effect = new SharpDX.Direct3D11.Effect(d, bCode); bCode = ShaderBytecode.Compile(Resources.BasicEffect, "BasicVS", "vs_5_0"); Device nativeDevice = (Device)device; ShaderSignature inputSignature = ShaderSignature.GetInputSignature(bCode); layout = ToDispose(new InputLayout(nativeDevice, inputSignature.Data, new InputElement[] { new InputElement("SV_Position", 0, SharpDX.DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, SharpDX.DXGI.Format.R32G32B32_Float, InputElement.AppendAligned, 0, InputClassification.PerVertexData, 0), new InputElement("WORLD", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 1, SharpDX.DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 2, SharpDX.DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 3, SharpDX.DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, InputElement.AppendAligned, 1, InputClassification.PerInstanceData, 1) })); }
private void BuildFX() { SharpDX.D3DCompiler.ShaderBytecode compiledShader = null; try { compiledShader = new SharpDX.D3DCompiler.ShaderBytecode(System.IO.File.ReadAllBytes("fx/lighting.fxo")); _fx = new D3D11.Effect(Device, compiledShader); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { Util.ReleaseCom(ref compiledShader); } _tech = _fx.GetTechniqueByName("LightTech"); _fxWVP = _fx.GetVariableByName("gWorldViewProj").AsMatrix(); _fxWorld = _fx.GetVariableByName("gWorld").AsMatrix(); _fxWIT = _fx.GetVariableByName("gWorldInvTranspose").AsMatrix(); _fxEyePosW = _fx.GetVariableByName("gEyePosW").AsVector(); _fxDirLight = _fx.GetVariableByName("gDirLight"); _fxPointLight = _fx.GetVariableByName("gPointLight"); _fxSpotLight = _fx.GetVariableByName("gSpotLight"); _fxMaterial = _fx.GetVariableByName("gMaterial"); _fxDiffuseMap = _fx.GetVariableByName("gDiffuseMap").AsShaderResource(); _fxRefractiveMap = _fx.GetVariableByName("gRefractiveMap").AsShaderResource(); _fxClipPlane = _fx.GetVariableByName("gClipPlane").AsVector(); _fxReflectViewProj = _fx.GetVariableByName("gReflectViewProj").AsMatrix(); _fxReflectiveMap = _fx.GetVariableByName("gReflectiveMap").AsShaderResource(); _fxgRefractionPositionMap = _fx.GetVariableByName("gRefractionPositionMap").AsShaderResource(); _fxUseStructBuf = _fx.GetVariableByName("gUseStructBuf").AsScalar(); _fxSolutionSR = _fx.GetVariableByName("gSolution").AsShaderResource(); }
private void CompileShader(Device device, string fullPath) { _File = fullPath; _CompiledEffect = ShaderBytecode.CompileFromFile(_File, "SpriteTech", "fx_5_0"); if (_CompiledEffect.HasErrors) { Log.Write("Shader compilation failed with status code: {0} - {1} | Path: {2}", _CompiledEffect.ResultCode.Code, _CompiledEffect.Message, _File); return; } _Effect = new Effect(device, _CompiledEffect); _EffectTechnique = _Effect.GetTechniqueByName("SpriteTech"); _SpriteMap = _Effect.GetVariableByName("SpriteTex").AsShaderResource(); var _EffectPass = _EffectTechnique.GetPassByIndex(0).Description.Signature; InputElement[] _LayoutDescription = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _InputLayout = new InputLayout(device, _EffectPass, _LayoutDescription); }
public override void Initialize() { Form.SizeChanged += (o, args) => { if (_swapChain == null) return; renderView.Dispose(); depthView.Dispose(); DisposeBuffers(); if (Form.WindowState == FormWindowState.Minimized) return; _width = Form.ClientSize.Width; _height = Form.ClientSize.Height; _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0); CreateBuffers(); SetSceneConstants(); }; _width = 1024; _height = 768; _nearPlane = 1.0f; ambient = new Color4(Color.Gray.ToArgb()); try { OnInitializeDevice(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Could not create DirectX 11 device."); return; } // shader.fx const ShaderFlags shaderFlags = ShaderFlags.None; //const ShaderFlags shaderFlags = ShaderFlags.Debug | ShaderFlags.SkipOptimization; ShaderBytecode shaderByteCode = LoadShader("shader.fx", shaderFlags); effect = new Effect(_device, shaderByteCode); EffectTechnique technique = effect.GetTechniqueByIndex(0); shadowGenPass = technique.GetPassByIndex(0); gBufferGenPass = technique.GetPassByIndex(1); debugDrawPass = technique.GetPassByName("debug"); BufferDescription sceneConstantsDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(ShaderSceneConstants)), Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None }; sceneConstantsBuffer = new Buffer(_device, sceneConstantsDesc); EffectConstantBuffer effectConstantBuffer = effect.GetConstantBufferByName("scene"); effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer); RasterizerStateDescription desc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, }; _immediateContext.Rasterizer.State = new RasterizerState(_device, desc); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; depthStencilState = new DepthStencilState(_device, depthDesc); DepthStencilStateDescription lightDepthStateDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc); // grender.fx shaderByteCode = LoadShader("grender.fx", shaderFlags); effect2 = new Effect(_device, shaderByteCode); technique = effect2.GetTechniqueByIndex(0); gBufferRenderPass = technique.GetPassByIndex(0); gBufferOverlayPass = technique.GetPassByIndex(1); info = new InfoText(_device); _meshFactory = new MeshFactory(this); MeshFactory = _meshFactory; CreateBuffers(); LibraryManager.LibraryStarted(); }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) hmd = oculus.Hmd_Create(0); else hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (hmd.ProductName == string.Empty) MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (! File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return false; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return false; } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return false; } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer<Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface<SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return true; }
public void TestMatrix() { // Compile a toolkit effect from a file var device = GraphicsDevice.New(DeviceCreationFlags.Debug); var result = new EffectCompiler().CompileFromFile("TestEffect.fx"); var effect = new Effect(device, result.EffectData); var worldViewProj = effect.Parameters["worldViewProj"]; var worlViewProjRowMajor = effect.Parameters["worlViewProjRowMajor"]; var worldViewProj3x3 = effect.Parameters["worldViewProj3x3"]; var matrix4x3 = effect.Parameters["matrix4x3"]; var matrix3x4RowMajor = effect.Parameters["matrix3x4RowMajor"]; var constantBuffer = effect.ConstantBuffers["$Globals"]; var sourceMatrix = Matrix.RotationX(0.5f); // Test column_major float4x4 (the matrix is transposed automatically by the effect) worldViewProj.SetValue(sourceMatrix); var destMatrix = worldViewProj.GetMatrix(); Assert.AreEqual(sourceMatrix, destMatrix); var destMatrix2 = constantBuffer.GetMatrix(worldViewProj.Offset); destMatrix2.Transpose(); Assert.AreEqual(sourceMatrix, destMatrix2); // Test row_major float4x4 (the matrix is transferred as is) worlViewProjRowMajor.SetValue(sourceMatrix); destMatrix = worlViewProjRowMajor.GetMatrix(); Assert.AreEqual(sourceMatrix, destMatrix); destMatrix2 = constantBuffer.GetMatrix(worlViewProjRowMajor.Offset); Assert.AreEqual(sourceMatrix, destMatrix2); // Test column_major float3x3 (the matrix is transposed automatically by the effect and only the 3x3 is transferred) var sourceMatrix3x3 = sourceMatrix; sourceMatrix3x3.Row4 = Vector4.Zero; sourceMatrix3x3.Column4 = Vector4.Zero; worldViewProj3x3.SetValue(sourceMatrix3x3); destMatrix = worldViewProj3x3.GetMatrix(); Assert.AreEqual(sourceMatrix3x3, destMatrix); var destMatrixFloats = constantBuffer.GetRange<float>(worldViewProj3x3.Offset, 3 * 3); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Assert.AreEqual(destMatrixFloats[j + i*3], sourceMatrix3x3[j, i]); } } effect.Dispose(); device.Dispose(); }
public void ApplyPlatformSpecificParams(Effect effect) { }
public WavesSimulator(IntPtr hInst) : base(hInst) { //Geometry Related Buffers _ballIB = null; _ballVB = null; _groundVB = null; _groundIB = null; _wavesVB = null; _wavesIB = null; _ballIndexCount = 0; _groundIndexCount = 0; //WVP Matrices _groundWorld = Matrix.Identity; _wavesWorld = Matrix.Translation(0, -2.0f, 0); _ballWorld = Matrix.Translation(-30, 15, 0); _view = Matrix.Identity; _proj = Matrix.Identity; _reflectView = Matrix.Identity; //Rendering Effects Related _fx = null; _fxWVP = null; _tech = null; _fxWorld = null; _fxWIT = null; _fxEyePosW = null; _fxDirLight = null; _fxPointLight = null; _fxSpotLight = null; _fxMaterial = null; _fxDiffuseMap = null; _fxRefractiveMap = null; _fxClipPlane = null; _fxReflectiveMap = null; _fxReflectViewProj = null; _fxUseStructBuf = null; _fxgRefractionPositionMap = null; //Textures and Views refractText = null; refractRenderTargetView = null; refractResourceView = null; reflectRenderTargetView = null; reflectResourceView = null; reflectText = null; positionMapRenderTargetView = null; positionMapResourceView = null; positionMapText = null; _groundMapSRV = null; _groundMap = null; //Input Format _inputLayout = null; //Camera Related _theta = 1.5f * MathF.PI; _phi = 0.1f * MathF.PI; _radius = 200.0f; _lastMousePos = new System.Drawing.Point(0, 0); _eyePosW = new Vector3(); //Shading and Lighting _alphaBlend = null; _dirLight = new DirectionalLight { Ambient = new Color4(0.2f, 0.2f, 0.2f, 1), Diffuse = new Color4(0.5f, 0.5f, 0.5f, 1), Specular = new Color4(0.5f, 0.5f, 0.5f, 1), Direction = new Vector3(0.57735f, -0.57735f, 0.57735f) }; _pointLight = new PointLight { Ambient = new Color4(0.3f, 0.3f, 0.3f, 1), Diffuse = new Color4(0.7f, 0.7f, 0.7f, 1), Specular = new Color4(0.7f, 0.7f, 0.7f, 1), Attenuation = new Vector3(0.1f, 0.1f, 0.1f), Range = 25.0f }; _spotLight = new SpotLight { Ambient = new Color4(0, 0, 0, 0), Diffuse = new Color4(1.0f, 1.0f, 1.0f, 1), Specular = Color.White, Attenuation = new Vector3(1.0f, 0.0f, 0.0f), Spot = 96.0f, Range = 10000.0f }; _landMaterial = new Material { Ambient = new Color4(1f, 1f, 1f, 1.0f), Diffuse = new Color4(1, 1, 1, 1.0f), Specular = new Color4(0.2f, 0.2f, 0.2f, 16.0f), Reflect = new Color4(1.0f, 1f, 1f, 1f) }; _wavesMaterial = new Material { Ambient = new Color4(1, 1, 1, 0.8f), Diffuse = new Color4(0.137f, 0.42f, 0.556f, 1.0f), Specular = new Color4(0.8f, 0.8f, 0.8f, 96.0f), Reflect = new Color4(2f, 1, 1, 1) //R component of Reflect is used for Gama Correction in Effect }; _disposed = false; MainWindowCaption = "Waves Simulator"; }
public void EffectsInitialization() { var effectByteCode = ShaderBytecode.CompileFromFile("C:\\Users\\Nat�lia\\Documents\\MPM\\5. ro�n�k\\Diplomovka\\grafika3D\\Grafika3D\\effect.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None); effect = new Effect(device, effectByteCode); techniquePosition = effect.GetTechniqueByName("Position"); passPosition = techniquePosition.GetPassByIndex(0); techniqueTexture = effect.GetTechniqueByName("Texture"); passTextureXY = techniqueTexture.GetPassByIndex(0); passTextureYZ = techniqueTexture.GetPassByIndex(1); passTextureZX = techniqueTexture.GetPassByIndex(2); var signature = passPosition.Description.Signature; inputLayout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }); var signatureTex = passTextureXY.Description.Signature; inputLayoutTex = new InputLayout(device, signatureTex, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); var samplerState = new SamplerState(device, new SamplerStateDescription() { AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, Filter = Filter.MinMagMipLinear, }); var effectSampler = effect.GetVariableByName("Sampler").AsSampler(); effectSampler.SetSampler(0, samplerState); }
private static InputLayout BuildLayout(Effect effect, Device device, string techniqueName, InputElement[] elements) { EffectTechnique technique = effect.GetTechniqueByName(techniqueName); var passDescription = technique.GetPassByIndex(0).Description; return new InputLayout(device, passDescription.Signature, elements); }
public void Initialize() { var direct2Dsettings = new RenderTarget.Configuration.CreationSettings( new Size(_settings.Width, _settings.Height), false, new SampleDescription(1, 0), RenderTarget.Configuration.RenderTargetClearSettings.Default, RenderTarget.Configuration.DepthStencilClearSettings.Default); RenderTargetDirect2D = _deviceManager.RenderTargetManager.CreateDirect2DRenderTarget(direct2Dsettings); _screenQuad = MeshFactory.CreateScreenQuad(_deviceManager.Device); //_screenQuadBinding = new VertexBufferBinding(_screenQuad, 20, 0); _effect = _deviceManager.ShaderCompiler.CreateEffectFromFile(@"..\..\Shaders\staging.fx"); _pass = _effect.GetTechniqueByIndex(0).GetPassByIndex(0); //_elements = new[] // { // new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), // new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), // }; _screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, VertexPositionTexture.InputElements); //_screenQuadBufferLayout = new InputLayout(_deviceManager.Device, _pass.Description.Signature, _elements); _shaderResource = _effect.GetVariableByName("source").AsShaderResource(); var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; _blendStateTransparent = new BlendState(_deviceManager.Device, bsd); }
private void LoadVisualizationEffect() { string engineDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string visEffectFile = Path.Combine(engineDir, @"Shaders\VisualizationEffect.fx"); var shaderByteCode = ShaderBytecode.CompileFromFile(visEffectFile, "fx_5_0", ShaderFlags.Debug); var effect = new Effect(this.GraphicsDevice, shaderByteCode); _visualizationEffect = new VisualizationEffect() { Effect = effect, World = effect.GetVariableByName("World").AsMatrix(), View = effect.GetVariableByName("View").AsMatrix(), Projection = effect.GetVariableByName("Projection").AsMatrix(), RenderScenePass0 = effect.GetTechniqueByName("RenderScene").GetPassByIndex(0) }; // Vertex structure the shader is expecting - very basic sample, just Position and Color. var elements = new[] { new InputElement("Position", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("Color", 0, Format.R32G32B32A32_Float, 16, 0) }; _inputLayout = new InputLayout(this.GraphicsDevice, _visualizationEffect.RenderScenePass0.Description.Signature, elements); }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="tso_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, TSOConfig tso_config) { this.tso_config = tso_config; SetControl(control); control.MouseDown += new MouseEventHandler(form_OnMouseDown); control.MouseMove += new MouseEventHandler(form_OnMouseMove); { device = new Device(DriverType.Hardware, DeviceCreationFlags.None); var desc = new SharpDX.DXGI.SwapChainDescription() { BufferCount = 1, Usage = SharpDX.DXGI.Usage.RenderTargetOutput, OutputHandle = control.Handle, IsWindowed = true, ModeDescription = new SharpDX.DXGI.ModeDescription(0, 0, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm), SampleDescription = DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float), Flags = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch, SwapEffect = SharpDX.DXGI.SwapEffect.Discard }; dxgi_factory = new SharpDX.DXGI.Factory(); swap_chain = new SharpDX.DXGI.SwapChain(dxgi_factory, device, desc); } ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (! File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return false; } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return false; } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (! File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return false; } techmap.Load(techmap_file); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; camera.Update(); DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); 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 = new[] { "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[] { 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(); }
private void LoadShaders() { //// Compile Vertex and Pixel shaders #if DEBUG CompilationResult effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.Debug | ShaderFlags.SkipOptimization | ShaderFlags.WarningsAreErrors /*| ShaderFlags.ForcePsSoftwareNoOpt*/, EffectFlags.None); #else CompilationResult effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None); #endif effect = new Effect(device, effectByteCode); }
/// <summary> /// 指定device上で開きます。 /// </summary> /// <param name="device">device</param> /// <param name="effect">effect</param> public void Open(Device device, Effect effect) { this.device = device; this.effect = effect; foreach (TSOMesh mesh in meshes) foreach (TSOSubMesh sub_mesh in mesh.sub_meshes) sub_mesh.WriteBuffer(device); foreach (TSOSubScript sub_script in sub_scripts) sub_script.WriteBuffer(device); texmap = new Dictionary<string, TSOTex>(); foreach (TSOTex tex in textures) { tex.Open(device); texmap[tex.name] = tex; } }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 3, ModeDescription= new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1,0), SwapEffect = SwapEffect.Sequential, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); Texture2DDescription depthBufferDesc; depthBufferDesc.Width = form.Width; depthBufferDesc.Height = form.Height; depthBufferDesc.MipLevels = 1; depthBufferDesc.ArraySize = 1; depthBufferDesc.Format = Format.D24_UNorm_S8_UInt; depthBufferDesc.SampleDescription.Count = 1; depthBufferDesc.SampleDescription.Quality = 0; depthBufferDesc.Usage = ResourceUsage.Default; depthBufferDesc.BindFlags = BindFlags.DepthStencil; depthBufferDesc.CpuAccessFlags = CpuAccessFlags.None ; depthBufferDesc.OptionFlags = ResourceOptionFlags.None; Texture2D DepthStencilTexture = new Texture2D(device, depthBufferDesc); DepthStencilViewDescription depthStencilViewDesc = new DepthStencilViewDescription(); depthStencilViewDesc.Format = Format.D24_UNorm_S8_UInt; depthStencilViewDesc.Dimension = DepthStencilViewDimension.Texture2D; depthStencilViewDesc.Texture2D.MipSlice = 0; DepthStencilView depthStencilView = new DepthStencilView(device, DepthStencilTexture, depthStencilViewDesc); context.OutputMerger.SetTargets(depthStencilView,renderView); DepthStencilStateDescription depthDesc = new DepthStencilStateDescription() { IsDepthEnabled = true, IsStencilEnabled = false, DepthWriteMask = DepthWriteMask.All, DepthComparison = Comparison.Less }; DepthStencilState depthStencilState = new DepthStencilState(device, depthDesc); RasterizerStateDescription rasdesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid, IsFrontCounterClockwise = true, DepthBias = 0, DepthBiasClamp = 0, SlopeScaledDepthBias = 0, IsDepthClipEnabled = true, IsMultisampleEnabled =true, }; context.Rasterizer.State = new RasterizerState(device, rasdesc); ////////////////////////////// var flags = (ppsteps | aiPostProcessSteps.aiProcess_GenSmoothNormals | // generate smooth normal vectors if not existing aiPostProcessSteps.aiProcess_SplitLargeMeshes | // split large, unrenderable meshes into submeshes aiPostProcessSteps.aiProcess_Triangulate | // triangulate polygons with more than 3 edges aiPostProcessSteps.aiProcess_ConvertToLeftHanded | // convert everything to D3D left handed space aiPostProcessSteps.aiProcess_SortByPType | // make 'clean' meshes which consist of a single typ of primitives (aiPostProcessSteps)0); // default model var path = @"jeep1.ms3d"; Importer importer = new Importer(); //var path = "man.3ds"; aiScene scene = importer.ReadFile(path, flags); String directory = null; if (scene != null) { directory = Path.GetDirectoryName(path); } else { MessageBox.Show("Failed to open file: " + path + ". Either Assimp screwed up or the path is not valid."); Application.Exit(); } SceneLoader SceneLoader = new SceneLoader(); List<model> models = new List<model>(); for (int i = 0; i < scene.mNumMeshes; i++) { models.Add(SceneLoader.CreateMesh(device, scene.mMeshes[i], scene.mMaterials,directory)); } ////////////////////////////// // Compile Vertex and Pixel shaders var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None); var effect = new Effect(device, effectByteCode); var technique = effect.GetTechniqueByIndex(0); var pass = technique.GetPassByIndex(0); // Layout from VertexShader input signature var passSignature = pass.Description.Signature; // Layout from VertexShader input signature var layout = new InputLayout( device, passSignature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); // Prepare All the stages context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.DepthStencilState = depthStencilState; Input input = new Input(form); //FreeLook FreeLook = new SharpExamples.FreeLook(input, (float)form.Width / (float)form.Height); CameraFirstPerson FreeLook = new CameraFirstPerson(input, 0, 0, Vector3.Zero, form.Width, form.Height); //FreeLook.SetEyeTarget(new Vector3(300), Vector3.Zero); Clock Clock = new SharpExamples.Clock(); Clock.Start(); effect.GetVariableByName("projection").AsMatrix().SetMatrix(FreeLook.Projection); // Main loop RenderLoop.Run(form, () => { foreach (var item in models) { context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; int SizeInBytes = Marshal.SizeOf(typeof(VertexPostitionTexture)); context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(item.vertex, SizeInBytes, 0)); context.InputAssembler.SetIndexBuffer(item.indices, Format.R32_UInt, 0); float elapsed = Clock.Update(); FreeLook.Update(elapsed); effect.GetVariableByName("view").AsMatrix().SetMatrix(FreeLook.View); effect.GetVariableByName("World").AsMatrix().SetMatrix(Matrix.Scaling(5)); effect.GetVariableByName("tex0").AsShaderResource().SetResource(item.ShaderResourceView); context.ClearRenderTargetView(renderView, Colors.Black); context.ClearDepthStencilView(depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1, 0); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(context); context.DrawIndexed(item.numberIndices, 0, 0); } swapChain.Present(0, PresentFlags.None); } }); // Release all resources foreach (var item in models) { item.vertex.Dispose(); item.indices.Dispose(); item.ShaderResourceView.Dispose(); } layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private static Effect GetEffect(Device device, byte[] effectBytes) { Effect effect; using (var dataStream = new DataStream(effectBytes.Length, true, true)) { dataStream.WriteRange(effectBytes); dataStream.Position = 0; using (var bytecode = new ShaderBytecode(dataStream)) { effect = new Effect(device, bytecode); } } return effect; }
/// <summary> /// deviceを作成します。 /// </summary> /// <param name="control">レンダリング先となるcontrol</param> /// <param name="ocu_config">設定</param> /// <returns>deviceの作成に成功したか</returns> public bool InitializeApplication(Control control, OcuConfig ocu_config) { this.ocu_config = ocu_config; oculus = new OculusWrap.Wrap(); // Initialize the Oculus runtime. bool success = oculus.Initialize(); if (!success) { MessageBox.Show("Failed to initialize the Oculus runtime library.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } // Use the head mounted display, if it's available, otherwise use the debug HMD. int numberOfHeadMountedDisplays = oculus.Hmd_Detect(); if (numberOfHeadMountedDisplays > 0) { hmd = oculus.Hmd_Create(0); } else { hmd = oculus.Hmd_CreateDebug(OculusWrap.OVR.HmdType.DK2); } if (hmd == null) { MessageBox.Show("Oculus Rift not detected.", "Uh oh", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } if (hmd.ProductName == string.Empty) { MessageBox.Show("The HMD is not enabled.", "There's a tear in the Rift", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Specify which head tracking capabilities to enable. hmd.SetEnabledCaps(OculusWrap.OVR.HmdCaps.LowPersistence | OculusWrap.OVR.HmdCaps.DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion hmd.ConfigureTracking(OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Orientation | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_MagYawCorrection | OculusWrap.OVR.TrackingCaps.ovrTrackingCap_Position, OculusWrap.OVR.TrackingCaps.None); // Create DirectX drawing device. device = new Device(SharpDX.Direct3D.DriverType.Hardware, DeviceCreationFlags.None); ctx = device.ImmediateContext; Stopwatch sw = new Stopwatch(); sw.Start(); string effect_file = Path.Combine(Application.StartupPath, @"toonshader.fx.bin"); if (!File.Exists(effect_file)) { Console.WriteLine("File not found: " + effect_file); return(false); } try { var shader_bytecode = ShaderBytecode.FromFile(effect_file); effect = new Effect(device, shader_bytecode); } catch (SharpDX.CompilationException e) { Console.WriteLine(e.Message + ": " + effect_file); return(false); } sw.Stop(); Console.WriteLine("toonshader.fx.bin read time: " + sw.Elapsed); string techmap_file = Path.Combine(Application.StartupPath, @"techmap.txt"); if (!File.Exists(techmap_file)) { Console.WriteLine("File not found: " + techmap_file); return(false); } techmap.Load(techmap_file); control.MouseDown += new MouseEventHandler(form_OnMouseDown); // Define the properties of the swap chain. SwapChainDescription swapChainDescription = DefineSwapChainDescription(control); // Create DirectX Graphics Interface factory, used to create the swap chain. dxgi_factory = new SharpDX.DXGI.Factory(); // Create the swap chain. swap_chain = new SwapChain(dxgi_factory, device, swapChainDescription); // Retrieve the back buffer of the swap chain. buf0 = swap_chain.GetBackBuffer <Texture2D>(0); buf0_view = new RenderTargetView(device, buf0); // Create a depth buffer, using the same width and height as the back buffer. Texture2DDescription depthBufferDescription = DefineDepthBufferDescription(control); // Create the depth buffer. ztex = new Texture2D(device, depthBufferDescription); ztex_view = new DepthStencilView(device, ztex); ctx.OutputMerger.SetRenderTargets(ztex_view, buf0_view); viewport = new Viewport(0, 0, hmd.Resolution.Width, hmd.Resolution.Height, 0.0f, 1.0f); ctx.Rasterizer.SetViewport(viewport); // Retrieve the DXGI device, in order to set the maximum frame latency. using (SharpDX.DXGI.Device1 dxgiDevice = device.QueryInterface <SharpDX.DXGI.Device1>()) { dxgiDevice.MaximumFrameLatency = 1; } layers = new OculusWrap.Layers(); layer_eye_fov = layers.AddLayerEyeFov(); CreateEyeTextures(); CreateMirrorTexture(control); World_variable = effect.GetVariableBySemantic("World").AsMatrix(); WorldView_variable = effect.GetVariableBySemantic("WorldView").AsMatrix(); WorldViewProjection_variable = effect.GetVariableBySemantic("WorldViewProjection").AsMatrix(); /* for HUD */ Projection_variable = effect.GetVariableBySemantic("Projection").AsMatrix(); LocalBoneMats_variable = effect.GetVariableByName("LocalBoneMats").AsMatrix(); LightDirForced_variable = effect.GetVariableByName("LightDirForced").AsVector(); UVSCR_variable = effect.GetVariableByName("UVSCR").AsVector(); cb_variable = effect.GetConstantBufferByName("cb"); ShadeTex_texture_variable = effect.GetVariableByName("ShadeTex_texture").AsShaderResource(); ColorTex_texture_variable = effect.GetVariableByName("ColorTex_texture").AsShaderResource(); //figures.Camera = camera; figures.TSOFileOpen += delegate(TSOFile tso) { tso.Open(device, effect); techmap.AssignTechniqueIndices(tso); }; // Define an input layout to be passed to the vertex shader. var technique = effect.GetTechniqueByIndex(0); il = new InputLayout(device, technique.GetPassByIndex(0).Description.Signature, TSOSubMesh.ie); // Setup the immediate context to use the shaders and model we defined. ctx.InputAssembler.InputLayout = il; DefineBlendState(); DefineDepthStencilState(); DefineRasterizerState(); main_camera = new Camera() { Position = ocu_config.Position, Rotation = Quaternion.Identity, }; directInput = new DirectInput(); keyboard = new Keyboard(directInput); keyboard.Acquire(); keyboardState = keyboard.GetCurrentState(); return(true); }
private static InputLayout GetStandardVertexLayout(Device device, Effect effect) { var type = typeof(StandardVertex); var positionOffset = Marshal.OffsetOf(type, PositionFieldName).ToInt32(); var uvOffset = Marshal.OffsetOf(type, UVFieldName).ToInt32(); var normalOffset = Marshal.OffsetOf(type, NormalFieldName).ToInt32(); var elements = new[] { new InputElement(PositionElementName, 0, Format.R32G32B32_Float, positionOffset, 0, InputClassification.PerVertexData, 0), new InputElement(UVElementName, 0, Format.R32G32_Float, uvOffset, 0, InputClassification.PerVertexData, 0), new InputElement(NormalElementName, 0, Format.R32G32B32_Float, normalOffset, 0, InputClassification.PerVertexData, 0), new InputElement(TransformName, 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement(TransformName, 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1), new InputElement(TransformName, 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1), new InputElement(TransformName, 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1) }; return BuildLayout(effect, device, Resources.StandardSmoothTechnique, elements); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 11 Sample using Effects11 system"); Configuration.EnableObjectTracking = true; // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_5_0", ShaderFlags.None, EffectFlags.None); var effect = new Effect(device, effectByteCode); var technique = effect.GetTechniqueByIndex(0); var pass = technique.GetPassByIndex(0); // Layout from VertexShader input signature var passSignature = pass.Description.Signature; var layout = new InputLayout(device, passSignature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { context.ClearRenderTargetView(renderView, Color.Black); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(context); context.Draw(3, 0); } swapChain.Present(0, PresentFlags.None); }); // Release all resources passSignature.Dispose(); effect.Dispose(); effectByteCode.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); device.Dispose(); swapChain.Dispose(); factory.Dispose(); }
private static VertexLayouts GetVertexLayouts(Device device, Effect effect) { return new VertexLayouts(GetStandardVertexLayout(device, effect), GetPrelitVertexLayout(device, effect)); }
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 = ShaderBytecode.Compile(SpriteFX, "SpriteTech", "fx_5_0"); { if (_compiledFX.HasErrors) return false; _effect = new Effect(_device, _compiledFX); { _spriteTech = _effect.GetTechniqueByName("SpriteTech"); _spriteMap = _effect.GetVariableByName("SpriteTex").AsShaderResource(); var pass = _spriteTech.GetPassByIndex(0).Description.Signature; InputElement[] layoutDesc = { new InputElement("POSITION", 0, SharpDX.DXGI.Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("TEXCOORD", 0, SharpDX.DXGI.Format.R32G32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 20, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, pass, 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 = new 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 = Marshal.AllocHGlobal(indices.Length * Marshal.SizeOf(indices[0])); Marshal.Copy(indices, 0, _indexBuffer, 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 = new SharpDX.Direct3D11.Buffer(_device, _indexBuffer, 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 = new BlendState(_device, transparentDesc); } } _initialized = true; return true; }
public EffectContainer(Device device, string EffectFile, InputElement[] _InputElement) { //Name = EffectFile; string extension = System.IO.Path.GetExtension(EffectFile); if (extension.ToLower() == ".fx") { IncludeFX includeFX = new IncludeFX(); //Компилируем шейдер в байткод #if !DEBUG //на время отладки шейдеров try #endif { SharpDX.Direct3D.ShaderMacro[] Macross = new SharpDX.Direct3D.ShaderMacro[6]; Macross[0] = new SharpDX.Direct3D.ShaderMacro("DX10_1", (Program.featureLevel > FeatureLevel.Level_10_0)? 1:0 ); Macross[1] = new SharpDX.Direct3D.ShaderMacro("SPLITCOUNT", PSSMsHelper.SplitsNumber); Macross[2] = new SharpDX.Direct3D.ShaderMacro("OCCLPPIXELINTEX", DrawHelper.OcclPixelInTex); Macross[3] = new SharpDX.Direct3D.ShaderMacro("SCREENX", Global.Settings.Width); Macross[4] = new SharpDX.Direct3D.ShaderMacro("SCREENY", Global.Settings.Height); using (ShaderBytecode bytecode = ShaderBytecode.CompileFromFile(EffectFile, "fx_5_0", #if DEBUG ShaderFlags.Debug | ShaderFlags.SkipOptimization | ShaderFlags.PreferFlowControl, #else ShaderFlags.OptimizationLevel3, #endif EffectFlags.None, Macross, includeFX)) { // Загрузим скомпилированный эффект в видеокарту renderEffect = new Effect(device, bytecode); } } #if !DEBUG catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error! Ошибкак чтения эффекта: " + EffectFile); new CompilationException(EffectFile); } #endif } else if (extension.ToLower() == ".ees") { try { System.IO.FileStream fs = new System.IO.FileStream(EffectFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, (int)fs.Length); fs.Close(); using (DataStream DS = new DataStream(bytes.Length, true, true)) { DS.Write(bytes, 0, bytes.Length); using (ShaderBytecode bytecode = new ShaderBytecode(DS)) { renderEffect = new Effect(device, bytecode); } } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("Error! Ошибкак чтения эффекта: " + EffectFile); new CompilationException(EffectFile); } } else { System.Windows.Forms.MessageBox.Show("Error! Не найден файл эффекта: " + EffectFile); new FileNotFoundException("Не найден файл", EffectFile); } //TODO изучить влияние renderEffect.Optimize(); TechniqueCount = renderEffect.Description.TechniqueCount; renderTechniques = new EffectTechnique[TechniqueCount]; // Загружаем техники из шейдера for (int i = 0; i < TechniqueCount; i++) { renderTechniques[i] = renderEffect.GetTechniqueByIndex(i); } // Выберем входную сигнатуру данных первого прохода var renderPassSignature = renderTechniques[0].GetPassByIndex(0).Description.Signature; if (_InputElement == null) { _InputElement= new InputElement[]{ 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), new InputElement("TEXCOORD", 1, Format.R32G32_Float, 32, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 40, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 52, 0)}; } //создаем входную конфигурвцию для стандартного меша layout = new InputLayout(device, renderPassSignature, _InputElement); }