Exemple #1
0
            public Lighting(Effect effect)
            {
                _singleLights = new SingleLight[4];

                _cbLighting = effect.GetConstantBufferByName("cbLights");
                HemisphericLightColorBelow         = _cbLighting.GetMemberByName("HemisphericLightColorBelow").AsVector();
                HemisphericLightColorAbove         = _cbLighting.GetMemberByName("HemisphericLightColorAbove").AsVector();
                HemisphericLightBelowToAboveVector = _cbLighting.GetMemberByName("HemisphericLightBelowToAboveVector").AsVector();

                LightPosX = _cbLighting.GetMemberByName("LightPosX").AsVector();
                LightPosY = _cbLighting.GetMemberByName("LightPosY").AsVector();
                LightPosZ = _cbLighting.GetMemberByName("LightPosZ").AsVector();

                LightDirX = _cbLighting.GetMemberByName("LightDirX").AsVector();
                LightDirY = _cbLighting.GetMemberByName("LightDirY").AsVector();
                LightDirZ = _cbLighting.GetMemberByName("LightDirZ").AsVector();

                LightColorR = _cbLighting.GetMemberByName("LightColorR").AsVector();
                LightColorG = _cbLighting.GetMemberByName("LightColorG").AsVector();
                LightColorB = _cbLighting.GetMemberByName("LightColorB").AsVector();

                LightRangeRcp       = _cbLighting.GetMemberByName("LightRangeRcp").AsVector();
                CapsuleLen          = _cbLighting.GetMemberByName("CapsuleLen").AsVector();
                SpotCosOuterCone    = _cbLighting.GetMemberByName("SpotCosOuterCone").AsVector();
                SpotCosInnerConeRcp = _cbLighting.GetMemberByName("SpotCosInnerConeRcp").AsVector();
            }
        protected override void Initialize()
        {
            base.Initialize();

            _pixelShaderConstantBuffer = ConstantBuffers["SamplingConstants"];
            _encodeConstantsParameter = _pixelShaderConstantBuffer.Parameters["EncodeConstants"];
        }
Exemple #3
0
        protected override void Initialize()
        {
            base.Initialize();

            _pixelShaderConstantBuffer = ConstantBuffers["SamplingConstants"];
            _encodeConstantsParameter  = _pixelShaderConstantBuffer.Parameters["EncodeConstants"];
        }
        public static void SetVariableBySemantic(this EffectConstantBuffer constantBuffer, string semantic, float value, bool throwIfNotFound)
        {
            var variable = RetrieveVariableBySemantic(constantBuffer, semantic, throwIfNotFound);

            if (variable.IsValid && variable.AsScalar() != null)
            {
                variable.AsScalar().Set(value);
            }
        }
        public static void SetVariableByName(this EffectConstantBuffer constantBuffer, string name, Matrix value, bool throwIfNotFound)
        {
            var variable = RetrieveVariableByName(constantBuffer, name, throwIfNotFound);

            if (variable != null && variable.AsMatrix() != null)
            {
                variable.AsMatrix().SetMatrix(value);
            }
        }
        public static void SetVariableByName(this EffectConstantBuffer constantBuffer, string name, int value, bool throwIfNotFound)
        {
            var variable = RetrieveVariableByName(constantBuffer, name, throwIfNotFound);

            if (variable.IsValid && variable.AsScalar() != null)
            {
                variable.AsScalar().Set(value);
            }
        }
        public static void SetVariableByName(this EffectConstantBuffer constantBuffer, string name, ShaderResourceView value, bool throwIfNotFound)
        {
            var variable = RetrieveVariableByName(constantBuffer, name, throwIfNotFound);

            if (variable.IsValid && variable.AsResource() != null)
            {
                variable.AsResource().SetResource(value);
            }
        }
        protected override void Initialize()
        {
            base.Initialize();

            this.Parameters["g_sampler"].SetResource(this.GraphicsDevice.SamplerStates.LinearClamp);

            m_perObConstBuf          = this.ConstantBuffers["PerObjectBuffer"];
            m_objectWorldMatrixParam = m_perObConstBuf.Parameters["g_chunkOffset"];
        }
        protected override void Initialize()
        {
            base.Initialize();

            _vertexShaderConstantBuffer = ConstantBuffers["VertexShaderConstants"];

            _viewMatrixParameter = _vertexShaderConstantBuffer.Parameters["ViewMatrix"];
            _projectionMatrixParameter = _vertexShaderConstantBuffer.Parameters["ProjectionMatrix"];
            _modelMatrixParameter = _vertexShaderConstantBuffer.Parameters["ModelMatrix"];
            _scaleFactorParameter = _vertexShaderConstantBuffer.Parameters["scaleFactor"];
        }
Exemple #10
0
        protected override void Initialize()
        {
            base.Initialize();

            _vertexShaderConstantBuffer = ConstantBuffers["VertexShaderConstants"];

            _viewMatrixParameter       = _vertexShaderConstantBuffer.Parameters["ViewMatrix"];
            _projectionMatrixParameter = _vertexShaderConstantBuffer.Parameters["ProjectionMatrix"];
            _modelMatrixParameter      = _vertexShaderConstantBuffer.Parameters["ModelMatrix"];
            _scaleFactorParameter      = _vertexShaderConstantBuffer.Parameters["scaleFactor"];
        }
Exemple #11
0
 public void Initialize(Device device, EffectConstantBuffer effectVariable, int size, T obj)
 {
     this.device    = device;
     this.target    = effectVariable;
     BufferDataBox  = new DataBox(0, 0, new DataStream(new[] { obj }, true, true));
     ConstantBuffer = new Buffer(device, new BufferDescription
     {
         SizeInBytes = size,
         BindFlags   = BindFlags.ConstantBuffer
     });
     OnInitialize();
 }
        /// <summary>
        /// EffectConstantBuffer経由で、シェーダーリソースビューをセットする
        /// </summary>
        /// <param name="p"></param>
        /// <param name="idx"></param>
        public void SetTextureBuffer(EffectConstantBuffer 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.SetTextureBuffer(m_aTxResourceView[idx]);
        }
        protected override void Initialize()
        {
            base.Initialize();

            _constantBuffer = ConstantBuffers["CB0"];

            _scaleParameter = _constantBuffer.Parameters["scale"];
            _offsetParameter = _constantBuffer.Parameters["offset"];

            _textureParameter = Parameters["tex"];

            Parameters["sam"].SetResource(GetSampler());
        }
Exemple #14
0
        protected override void Initialize()
        {
            base.Initialize();

            _constantBuffer = ConstantBuffers["CB0"];

            _scaleParameter  = _constantBuffer.Parameters["scale"];
            _offsetParameter = _constantBuffer.Parameters["offset"];

            _textureParameter = Parameters["tex"];

            Parameters["sam"].SetResource(GetSampler());
        }
Exemple #15
0
        protected override void Initialize()
        {
            base.Initialize();

            if (this.Parameters.Contains("blockSampler"))
            {
                this.Parameters["blockSampler"].SetResource(this.GraphicsDevice.SamplerStates.LinearClamp);
            }

            m_perObConstBuf          = this.ConstantBuffers["PerObjectBuffer"];
            m_objectWorldMatrixParam = m_perObConstBuf.Parameters["g_chunkOffset"];

            CreateGameColorBuffer();
        }
        protected override void Initialize()
        {
            base.Initialize();

            _colorTextureParameter = Parameters["ColorTexture"];
            _colorResidencyParameter = Parameters["ColorResidency"];
            _normalTextureParameter = Parameters["NormalTexture"];
            _normalResidencyParameter = Parameters["NormalResidency"];

            Parameters["Trilinear"].SetResource(GraphicsDevice.SamplerStates.AnisotropicWrap);
            Parameters["MaxFilter"].SetResource(GraphicsDevice.SamplerStates.LinearWrap);

            _pixelShaderConstantBuffer = ConstantBuffers["PixelShaderConstants"];

            _sunPositionParameter = _pixelShaderConstantBuffer.Parameters["SunPosition"];
        }
Exemple #17
0
        internal protected virtual void SetupPerBatchParameters(Viewer viewer)
        {
            if (viewer == null)
            {
                throw new ArgumentNullException("viewer");
            }

            EffectConstantBuffer perBatchParameters = Effect.GetConstantBufferByName("PerBatch");

            perBatchParameters.SetVariableBySemantic(StandartSemantics.WorldMatrix,
                                                     WorldMatrix, false);
            perBatchParameters.SetVariableBySemantic(StandartSemantics.WorldViewMatrix,
                                                     WorldMatrix * viewer.ViewMatrix, false);
            perBatchParameters.SetVariableBySemantic(StandartSemantics.WorldViewProjectionMatrix,
                                                     WorldMatrix * viewer.ViewMatrix * viewer.ProjectionMatrix, false);
        }
Exemple #18
0
        protected override void Initialize()
        {
            base.Initialize();

            _colorTextureParameter    = Parameters["ColorTexture"];
            _colorResidencyParameter  = Parameters["ColorResidency"];
            _normalTextureParameter   = Parameters["NormalTexture"];
            _normalResidencyParameter = Parameters["NormalResidency"];

            Parameters["Trilinear"].SetResource(GraphicsDevice.SamplerStates.AnisotropicWrap);
            Parameters["MaxFilter"].SetResource(GraphicsDevice.SamplerStates.LinearWrap);

            _pixelShaderConstantBuffer = ConstantBuffers["PixelShaderConstants"];

            _sunPositionParameter = _pixelShaderConstantBuffer.Parameters["SunPosition"];
        }
        public void 初期化する(EffectConstantBuffer d3dエフェクト定数バッファ, T 定数バッファのレイアウト構造体, int 定数バッファのレイアウト構造体のサイズbytes)
        {
            _D3Dエフェクト定数バッファ = d3dエフェクト定数バッファ;

            _BufferDataStream = DataStream.Create(
                new[] { 定数バッファのレイアウト構造体 },
                canRead: true,
                canWrite: true,
                pinBuffer: true);   // copy & pinned

            D3D定数バッファ = new Buffer(
                RenderContext.Instance.DeviceManager.D3DDevice,
                new BufferDescription {
                SizeInBytes = 定数バッファのレイアウト構造体のサイズbytes,
                BindFlags   = BindFlags.ConstantBuffer,
            });
        }
        private static EffectVariable RetrieveVariableBySemantic(EffectConstantBuffer constantBuffer, string semantic, bool throwIfNotFound)
        {
            if (constantBuffer == null)
            {
                throw new ArgumentNullException("constantBuffer");
            }
            if (String.IsNullOrEmpty(semantic))
            {
                throw new ArgumentNullException("semantic");
            }

            EffectVariable variable = constantBuffer.GetMemberBySemantic(semantic);

            if (!variable.IsValid && throwIfNotFound)
            {
                throw new ArgumentException(string.Format("Can't retrieve variable with given semantic {0}.", semantic), "semantic");
            }
            return(variable);
        }
        private static EffectVariable RetrieveVariableByName(EffectConstantBuffer constantBuffer, string name, bool throwIfNotFound)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }
            if (constantBuffer == null)
            {
                throw new ArgumentNullException("constantBuffer");
            }

            EffectVariable variable = constantBuffer.GetMemberByName(name);

            if (!variable.IsValid && throwIfNotFound)
            {
                throw new ArgumentException(string.Format("Can't retrieve variable with given name {0}.", name), "name");
            }
            return(variable);
        }
Exemple #22
0
        public static void CompareConstantBuffer(EffectConstantBuffer reflectionEffectBuffer, Fx10.EffectBuffer buffer)
        {
            var desc = reflectionEffectBuffer.Description;

            Assert.AreEqual(desc.Name, buffer.Name);
            Assert.AreEqual(desc.Semantic ?? "", "");
            Assert.AreEqual((uint)desc.Flags, 0);
            Assert.AreEqual(desc.AnnotationCount, 0);
            Assert.AreEqual(desc.BufferOffset, 0);
            Assert.AreEqual(desc.ExplicitBindPoint, buffer.RegisterNumber == uint.MaxValue ? 0 : buffer.RegisterNumber);
            Assert.AreEqual(reflectionEffectBuffer.TypeInfo.Description.Type, (ShaderVariableType)buffer.Type);
            if (reflectionEffectBuffer.TypeInfo.Description.Type == ShaderVariableType.ConstantBuffer)
            {
                var cbufferDesc = reflectionEffectBuffer.GetConstantBuffer().Description;
                //TODO: Compare cbufferDesc
            }
            else
            {
                var tbufferDesc = reflectionEffectBuffer.GetTextureBuffer().Description;
                //TODO: Compare tbufferDesc
            }
        }
Exemple #23
0
        internal void SetupGlobalParameters(Viewer viewer, Timer timer)
        {
            if (viewer == null)
            {
                throw new ArgumentNullException("viewer");
            }
            if (timer == null)
            {
                throw new ArgumentNullException("timer");
            }

            EffectConstantBuffer perViewParameters = Effect.GetConstantBufferByName("Global");

            perViewParameters.SetVariableBySemantic(StandartSemantics.ViewMatrix,
                                                    viewer.ViewMatrix, false);
            perViewParameters.SetVariableBySemantic(StandartSemantics.ProjectionMatrix,
                                                    viewer.ProjectionMatrix, false);
            perViewParameters.SetVariableBySemantic(StandartSemantics.ViewProjectionMatrix,
                                                    viewer.ViewMatrix * viewer.ProjectionMatrix, false);
            perViewParameters.SetVariableBySemantic(StandartSemantics.TotalTime, (float)timer.Time.Total, false);
            perViewParameters.SetVariableBySemantic(StandartSemantics.ElapsedTime, (float)timer.Time.Elapsed, false);
        }
Exemple #24
0
        internal EffectConstantBuffer GetOrCreateConstantBuffer(GraphicsDevice context, EffectData.ConstantBuffer bufferRaw)
        {
            EffectConstantBuffer constantBuffer;
            // Is the effect is using shared constant buffers via the EffectPool?
            if (ShareConstantBuffers)
            {
                // Use the pool to share constant buffers
                constantBuffer = Pool.GetOrCreateConstantBuffer(context, bufferRaw);
            }
            else
            {
                // ----------------------------------------------------------------------------
                // Get an existing constant buffer having the same name/sizel/ayout/parameters
                // ----------------------------------------------------------------------------
                var bufferKey = new EffectConstantBufferKey(bufferRaw);
                if (!effectConstantBuffersCache.TryGetValue(bufferKey, out constantBuffer))
                {
                    // 4) If this buffer doesn't exist, create a new one and register it.
                    constantBuffer = new EffectConstantBuffer(context, bufferRaw);
                    effectConstantBuffersCache.Add(bufferKey, constantBuffer);
                    DisposeCollector.Collect(constantBuffer);
                }
            }

            return constantBuffer;
        }
Exemple #25
0
 public ConstantBufferLink(EffectConstantBuffer constantBuffer, int resourceIndex)
 {
     ConstantBuffer = constantBuffer;
     ResourceIndex = resourceIndex;
 }
Exemple #26
0
		public void Attach(Device hostDevice, PointD2D hostSize)
		{
			if (hostDevice == null)
				throw new ArgumentNullException(nameof(hostDevice));

			_hostDevice = hostDevice;
			_hostSize = hostSize;

			Device device = _hostDevice;

			using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Altaxo.CompiledShaders.Effects.Lighting.cso"))
			{
				if (null == stream)
					throw new InvalidOperationException(string.Format("Compiled shader resource not found: {0}", "Altaxo.CompiledShaders.Effects.Lighting.cso"));

				using (var shaderBytes = ShaderBytecode.FromStream(stream))
				{
					_lightingEffect = new Effect(device, shaderBytes);
				}
			}

			int i;

			for (i = 0; i < _layoutNames.Length; ++i)
			{
				string techniqueName = "Shade_" + _layoutNames[i];
				_renderLayouts[i].technique = this._lightingEffect.GetTechniqueByName(techniqueName);
				_renderLayouts[i].pass = _renderLayouts[i].technique.GetPassByIndex(0);

				if (null == _renderLayouts[i].technique || !_renderLayouts[i].technique.IsValid)
					throw new InvalidProgramException(string.Format("Technique {0} was not found or is invalid", techniqueName));
				if (null == _renderLayouts[i].pass || !_renderLayouts[i].pass.IsValid)
					throw new InvalidProgramException(string.Format("Pass[0] of technique {0} was not found or is invalid", techniqueName));
			}

			i = 0;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
																								});

			i = 1;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
																								});

			i = 2;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
																								});

			i = 3;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0)
																								});

			i = 4;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
																																new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0)
																								});

			i = 5;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0)
																								});

			i = 6;
			_renderLayouts[i].VertexLayout = new InputLayout(device, _renderLayouts[i].pass.Description.Signature, new[] {
																																new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
																																new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
																																new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
																								});

			// Create Constant Buffers
			//_constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
			//_constantBufferForColor = new Buffer(device, Utilities.SizeOf<Vector4>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
			//_constantBufferForSixPlanes = new Buffer(device, Utilities.SizeOf<Vector4>() * 6, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

			// View transformation variables
			_cbViewTransformation = this._lightingEffect.GetConstantBufferByName("cbViewTransformation");
			_evWorldViewProj = _cbViewTransformation.GetMemberByName("WorldViewProj").AsMatrix();
			_evEyePosition = _cbViewTransformation.GetMemberByName("EyePosition").AsVector();

			_cbMaterial = this._lightingEffect.GetConstantBufferByName("cbMaterial");
			_evMaterialDiffuseColor = _cbMaterial.GetMemberByName("MaterialDiffuseColor").AsVector();
			_evMaterialSpecularExponent = _cbMaterial.GetMemberByName("MaterialSpecularExponent").AsScalar();
			_evMaterialSpecularExponent.Set(4.0f);
			_evMaterialSpecularIntensity = _cbMaterial.GetMemberByName("MaterialSpecularIntensity").AsScalar();
			_evMaterialSpecularIntensity.Set(1.0f);
			_evMaterialDiffuseIntensity = _cbMaterial.GetMemberByName("MaterialDiffuseIntensity").AsScalar();
			_evMaterialMetalnessValue = _cbMaterial.GetMemberByName("MaterialMetalnessValue").AsScalar();
			_evMaterialMetalnessValue.Set(0.75f);

			// Color providers
			BindTextureFor1DColorProviders();

			// Clip plane variables
			_cbClipPlanes = this._lightingEffect.GetConstantBufferByName("cbClipPlanes");
			for (i = 0; i < 6; ++i)
			{
				_evClipPlanes[i] = _cbClipPlanes.GetMemberByName("ClipPlane" + i.ToString(System.Globalization.CultureInfo.InvariantCulture)).AsVector();
			}

			// Lighting variables

			_lighting.Initialize(_lightingEffect);
			_lighting.SetDefaultLighting();

			// --------------------
			if (_drawing != null)
			{
				BringDrawingIntoBuffers(_drawing);
			}

			if (null != _markerGeometry)
			{
				BringMarkerGeometryIntoDeviceBuffers(_markerGeometry);
			}

			if (null != _overlayGeometry)
			{
				BringOverlayGeometryIntoDeviceBuffers(_overlayGeometry);
			}
		}
Exemple #27
0
        /// <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);

            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.B8G8R8A8_UNorm),
                SampleDescription = new SharpDX.DXGI.SampleDescription(4, 0),
                Flags             = SharpDX.DXGI.SwapChainFlags.AllowModeSwitch,
                SwapEffect        = SharpDX.DXGI.SwapEffect.Discard
            };

            Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swap_chain);

            //DetectSampleDescription(device, SharpDX.DXGI.Format.D32_Float);

            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 normal in view */
            View_variable = effect.GetVariableBySemantic("View").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);
        }
Exemple #28
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                _width  = Form.ClientSize.Width;
                _height = Form.ClientSize.Height;

                if (_swapChain == null)
                {
                    return;
                }

                renderView.Dispose();
                depthView.Dispose();
                _swapChain.ResizeBuffers(_swapChain.Description.BufferCount, 0, 0, Format.Unknown, 0);

                CreateBuffers();
                SetSceneConstants();
            };

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

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

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


            // shader.fx

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

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

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

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

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

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

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

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

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

            depthStencilState = new DepthStencilState(_device, depthDesc);

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

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

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

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

            Buffer quad = DemoFramework.SharpDX.MeshFactory.CreateScreenQuad(_device);

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

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

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


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

            CreateBuffers();
            LibraryManager.LibraryStarted();
        }
Exemple #29
0
			public void Initialize(Effect effect)
			{
				_singleLights = new SingleLight[4];

				_cbLighting = effect.GetConstantBufferByName("cbLights");
				HemisphericLightColorBelow = _cbLighting.GetMemberByName("HemisphericLightColorBelow").AsVector();
				HemisphericLightColorAbove = _cbLighting.GetMemberByName("HemisphericLightColorAbove").AsVector();
				HemisphericLightBelowToAboveVector = _cbLighting.GetMemberByName("HemisphericLightBelowToAboveVector").AsVector();

				LightPosX = _cbLighting.GetMemberByName("LightPosX").AsVector();
				LightPosY = _cbLighting.GetMemberByName("LightPosY").AsVector();
				LightPosZ = _cbLighting.GetMemberByName("LightPosZ").AsVector();

				LightDirX = _cbLighting.GetMemberByName("LightDirX").AsVector();
				LightDirY = _cbLighting.GetMemberByName("LightDirY").AsVector();
				LightDirZ = _cbLighting.GetMemberByName("LightDirZ").AsVector();

				LightColorR = _cbLighting.GetMemberByName("LightColorR").AsVector();
				LightColorG = _cbLighting.GetMemberByName("LightColorG").AsVector();
				LightColorB = _cbLighting.GetMemberByName("LightColorB").AsVector();

				LightRangeRcp = _cbLighting.GetMemberByName("LightRangeRcp").AsVector();
				CapsuleLen = _cbLighting.GetMemberByName("CapsuleLen").AsVector();
				SpotCosOuterCone = _cbLighting.GetMemberByName("SpotCosOuterCone").AsVector();
				SpotCosInnerConeRcp = _cbLighting.GetMemberByName("SpotCosInnerConeRcp").AsVector();
			}
Exemple #30
0
        /// <summary>
        ///     コンストラクタ
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="context"></param>
        /// <param name="effect">解釈対象のエフェクト</param>
        /// <param name="model">使用対象のモデル</param>
        /// <param name="loader"></param>
        private MMEEffectManager(string fileName, RenderContext context, SlimDX.Direct3D11.Effect effect, IDrawable model, ISubresourceLoader loader)
        {
            this.fileName     = fileName;
            SubresourceLoader = loader;
            if (!fileName.Equals(MMFDefaultShaderResourcePath))
            {
                //ファイルパスがデフォルトのシェーダーと等しくない時は、デフォルトのシェーダーも読み込んでおく。
                DefaultShader = LoadFromResource(MMFDefaultShaderResourcePath, model, context, new BasicSubresourceLoader("Shader"));
            }
            else
            {
                DefaultShader = this; //等しい時は自身がデフォルトのシェーダーと等しい。
            }
            Context    = context;
            EffectFile = effect;
            EffectInfo = new MMEEffectInfo(effect);
            ActiveSubscriberByMaterial = new Dictionary <EffectVariable, SubscriberBase>();
            ActiveSubscriberByModel    = new Dictionary <EffectVariable, SubscriberBase>();
            ActivePeculiarSubscriber   = new Dictionary <EffectVariable, PeculiarValueSubscriberBase>();
            Techniques = new List <MMEEffectTechnique>();
            RenderColorTargetViewes   = new Dictionary <string, RenderTargetView>();
            RenderDepthStencilTargets = new Dictionary <string, DepthStencilView>();
            this.model = model;
            //グローバル変数の登録
            int valCount = effect.Description.GlobalVariableCount;

            for (int i = 0; i < valCount; i++)
            {
                string semantic         = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[0-9]", "");
                string semanticIndexStr = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[^0-9]", "");
                int    semanticIndex    = string.IsNullOrEmpty(semanticIndexStr)?0:int.Parse(semanticIndexStr);
                string typeName         = effect.GetVariableByIndex(i).GetVariableType().Description.TypeName.ToLower();
                semantic = semantic.ToUpper(); //小文字でもいいようにするため大文字に全て変換
                if (EffectSubscriber.ContainsKey(semantic))
                {                              //通常はセマンティクスに応じて登録
                    SubscriberBase subs     = EffectSubscriber[semantic];
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                    else
                    {
                        ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                }
                else if (typeName.Equals("texture") || typeName.Equals("texture2d") || typeName.Equals("texture3d") ||
                         typeName.Equals("texturecube")) //テクスチャのみ例外で、変数型に応じて登録する
                {
                    SubscriberBase subs     = new TextureSubscriber();
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                }
                else//特殊変数は変数名に応じて登録する
                {
                    string name = effect.GetVariableByIndex(i).Description.Name;
                    name = name.ToLower();
                    if (PeculiarEffectSubscriber.ContainsKey(name))
                    {
                        ActivePeculiarSubscriber.Add(effect.GetVariableByIndex(i), PeculiarEffectSubscriber[name]);
                    }
                }
            }
            //定数バッファの登録
            valCount = effect.Description.ConstantBufferCount;
            for (int i = 0; i < valCount; i++)
            {
                string name = effect.GetConstantBufferByIndex(i).Description.Name;
                name = name.ToUpper();
                if (EffectSubscriber.ContainsKey(name))
                {
                    SubscriberBase       subs     = EffectSubscriber[name]; //定数バッファにはセマンティクスが付けられないため、変数名で代用
                    EffectConstantBuffer variable = effect.GetConstantBufferByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                    else
                    {
                        ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                }
            }

            int subsetCount = model is ISubsetDivided ? ((ISubsetDivided)model).SubsetCount : 1;

            foreach (EffectTechnique t in EffectInfo.SortedTechnique)//MMEEffectTechniqueもソートしておく
            {
                //テクニックをすべて読みだす
                Techniques.Add(new MMEEffectTechnique(this, t, subsetCount, context));
            }
        }
Exemple #31
0
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="context"></param>
        /// <param name="effect">Effects of being interpreted</param>
        /// <param name="model">Want to use models</param>
        /// <param name="loader"></param>
        private MMEEffectManager(string fileName, RenderContext context, Effect effect, IDrawable model, ISubresourceLoader loader)
        {
            this.fileName          = fileName;
            this.SubresourceLoader = loader;
            if (!fileName.Equals(MMFDefaultShaderResourcePath))
            {
                //The default shaders loaded and the default file path is not equal:。
                this.DefaultShader = LoadFromResource(MMFDefaultShaderResourcePath, model, context, new BasicSubresourceLoader("Shader"));
            }
            else
            {
                this.DefaultShader = this; //Equal to itself is equal to the default shader。
            }
            this.Context    = context;
            this.EffectFile = effect;
            this.EffectInfo = new MMEEffectInfo(effect);
            this.ActiveSubscriberByMaterial = new Dictionary <EffectVariable, SubscriberBase>();
            this.ActiveSubscriberByModel    = new Dictionary <EffectVariable, SubscriberBase>();
            this.ActivePeculiarSubscriber   = new Dictionary <EffectVariable, PeculiarValueSubscriberBase>();
            this.Techniques = new List <MMEEffectTechnique>();
            this.RenderColorTargetViewes   = new Dictionary <string, RenderTargetView>();
            this.RenderDepthStencilTargets = new Dictionary <string, DepthStencilView>();
            this.model = model;
            //Creating global variables
            int valCount = effect.Description.GlobalVariableCount;

            for (int i = 0; i < valCount; i++)
            {
                string semantic         = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[0-9]", "");
                string semanticIndexStr = Regex.Replace(effect.GetVariableByIndex(i).Description.Semantic, "[^0-9]", "");
                int    semanticIndex    = string.IsNullOrEmpty(semanticIndexStr)?0:int.Parse(semanticIndexStr);
                string typeName         = effect.GetVariableByIndex(i).GetVariableType().Description.TypeName.ToLower();
                semantic = semantic.ToUpper(); //A good case for all converted to uppercase
                if (EffectSubscriber.ContainsKey(semantic))
                {                              //Usually the register according to the semantics
                    SubscriberBase subs     = EffectSubscriber[semantic];
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        this.ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                    else
                    {
                        this.ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                    }
                }
                else if (typeName.Equals("texture") || typeName.Equals("texture2d") || typeName.Equals("texture3d") ||
                         typeName.Equals("texturecube")) //Textures only in exceptions, depending on the variable type to register
                {
                    SubscriberBase subs     = new TextureSubscriber();
                    EffectVariable variable = effect.GetVariableByIndex(i);
                    subs.CheckType(variable);
                    this.ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, semanticIndex));
                }
                else//Special variable to register according to the variable name
                {
                    string name = effect.GetVariableByIndex(i).Description.Name;
                    name = name.ToLower();
                    if (PeculiarEffectSubscriber.ContainsKey(name))
                    {
                        this.ActivePeculiarSubscriber.Add(effect.GetVariableByIndex(i), PeculiarEffectSubscriber[name]);
                    }
                }
            }
            //Constant buffer register
            valCount = effect.Description.ConstantBufferCount;
            for (int i = 0; i < valCount; i++)
            {
                string name = effect.GetConstantBufferByIndex(i).Description.Name;
                name = name.ToUpper();
                if (EffectSubscriber.ContainsKey(name))
                {
                    SubscriberBase       subs     = EffectSubscriber[name]; //A constant buffer semantics, so instead the variable name
                    EffectConstantBuffer variable = effect.GetConstantBufferByIndex(i);
                    subs.CheckType(variable);
                    if (subs.UpdateTiming == UpdateBy.Material)
                    {
                        this.ActiveSubscriberByMaterial.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                    else
                    {
                        this.ActiveSubscriberByModel.Add(variable, subs.GetSubscriberInstance(variable, context, this, 0));
                    }
                }
            }

            int subsetCount = model is ISubsetDivided ? ((ISubsetDivided)model).SubsetCount : 1;

            foreach (EffectTechnique t in this.EffectInfo.SortedTechnique)//MMEEffectTechnique are sorted by
            {
                //All techniques will be read
                this.Techniques.Add(new MMEEffectTechnique(this, t, subsetCount, context));
            }
        }
Exemple #32
0
        /// <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);
        }
Exemple #33
0
        /// <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;
        }
Exemple #34
0
        /// <summary>
        /// Attaches the scene to the device specified in <paramref name="device"/>, and allocate resources specific to that device.
        /// </summary>
        /// <param name="device">The device to attach to.</param>
        /// <param name="hostSize">The size of the device.</param>
        public void Attach(Device device, PointD2D hostSize)
        {
            if (null != _cachedDevice)
            {
                throw new InvalidOperationException("Try to attach to device without deattach former device!");
            }

            _cachedDevice = device ?? throw new ArgumentNullException(nameof(device));
            _hostSize     = hostSize;

            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Altaxo.CompiledShaders.Effects.Lighting.cso"))
            {
                if (null == stream)
                {
                    throw new InvalidOperationException(string.Format("Compiled shader resource not found: {0}", "Altaxo.CompiledShaders.Effects.Lighting.cso"));
                }

                using (var shaderBytes = ShaderBytecode.FromStream(stream))
                {
                    _lightingEffect = new Effect(device, shaderBytes);
                }
            }



            for (int i = 0; i < _layoutNames.Length; ++i)
            {
                string techniqueName = "Shade_" + _layoutNames[i];
                var    technique     = _lightingEffect.GetTechniqueByName(techniqueName);
                if (null == technique || !technique.IsValid)
                {
                    throw new InvalidProgramException(string.Format("Technique {0} was not found or is invalid", techniqueName));
                }

                var pass = technique.GetPassByIndex(0);
                if (null == pass || !pass.IsValid)
                {
                    throw new InvalidProgramException(string.Format("Pass[0] of technique {0} was not found or is invalid", techniqueName));
                }

                InputLayout inputLayout;
                switch (i)
                {
                case 0:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0)
                    });
                    break;

                case 1:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
                    });
                    break;

                case 2:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0)
                    });
                    break;

                case 3:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0)
                    });
                    break;

                case 4:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
                        new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 32, 0)
                    });
                    break;

                case 5:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32A32_Float, 16, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 32, 0)
                    });
                    break;

                case 6:
                    inputLayout = new InputLayout(device, pass.Description.Signature, new[] {
                        new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0),
                        new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0),
                        new InputElement("TEXCOORD", 0, Format.R32G32_Float, 24, 0)
                    });
                    break;

                default:
                    throw new NotImplementedException();
                }

                _renderLayouts[i] = new RenderLayout(technique, pass, inputLayout);
            }



            // Create Constant Buffers
            //_constantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
            //_constantBufferForColor = new Buffer(device, Utilities.SizeOf<Vector4>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);
            //_constantBufferForSixPlanes = new Buffer(device, Utilities.SizeOf<Vector4>() * 6, ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None);

            // View transformation variables
            _cbViewTransformation = _lightingEffect.GetConstantBufferByName("cbViewTransformation");
            _evWorldViewProj      = _cbViewTransformation.GetMemberByName("WorldViewProj").AsMatrix();
            _evEyePosition        = _cbViewTransformation.GetMemberByName("EyePosition").AsVector();

            _cbMaterial                 = _lightingEffect.GetConstantBufferByName("cbMaterial");
            _evMaterialDiffuseColor     = _cbMaterial.GetMemberByName("MaterialDiffuseColor").AsVector();
            _evMaterialSpecularExponent = _cbMaterial.GetMemberByName("MaterialSpecularExponent").AsScalar();
            _evMaterialSpecularExponent.Set(4.0f);
            _evMaterialSpecularIntensity = _cbMaterial.GetMemberByName("MaterialSpecularIntensity").AsScalar();
            _evMaterialSpecularIntensity.Set(1.0f);
            _evMaterialDiffuseIntensity = _cbMaterial.GetMemberByName("MaterialDiffuseIntensity").AsScalar();
            _evMaterialMetalnessValue   = _cbMaterial.GetMemberByName("MaterialMetalnessValue").AsScalar();
            _evMaterialMetalnessValue.Set(0.75f);

            // Color providers
            BindTextureFor1DColorProviders();

            // Clip plane variables
            _cbClipPlanes = _lightingEffect.GetConstantBufferByName("cbClipPlanes");
            for (int i = 0; i < 6; ++i)
            {
                _evClipPlanes[i] = _cbClipPlanes.GetMemberByName("ClipPlane" + i.ToString(System.Globalization.CultureInfo.InvariantCulture)).AsVector();
            }

            // Lighting variables

            _lighting = new Lighting(_lightingEffect);
            _lighting.SetDefaultLighting();

            // -------------------- now draw the scene again with the new attached device --------------

            if (null != _altaxoCamera && null != _altaxoLightSettings)
            {
                if (_altaxoDrawingGeometry != null)
                {
                    BringDrawingIntoBuffers(_altaxoDrawingGeometry);
                }

                if (null != _altaxoMarkerGeometry)
                {
                    BringMarkerGeometryIntoDeviceBuffers(_altaxoMarkerGeometry);
                }

                if (null != _altaxoOverlayGeometry)
                {
                    BringOverlayGeometryIntoDeviceBuffers(_altaxoOverlayGeometry);
                }
            }
        }
Exemple #35
0
 private static Buffer DefaultConstantBufferAllocator(GraphicsDevice device, EffectPool pool, EffectConstantBuffer constantBuffer)
 {
     return Buffer.Constant.New(device, constantBuffer.Size);
 }
Exemple #36
0
        public override void Initialize()
        {
            Form.SizeChanged += (o, args) =>
            {
                if (_swapChain == null)
                {
                    return;
                }

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

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

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

                CreateBuffers();
                SetSceneConstants();
            };

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

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

            try
            {
                OnInitializeDevice();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Could not create DirectX 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);

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

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

            depthStencilState = new DepthStencilState(_device, depthDesc);

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

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

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

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

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

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

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

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

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

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

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

            effectConstantBuffer.SetConstantBuffer(sceneConstantsBuffer);

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

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

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

            depthStencilState = new DepthStencilState(_device, depthDesc);

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

            lightDepthStencilState = new DepthStencilState(_device, lightDepthStateDesc);


            // grender.fx

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

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

            Buffer quad = MeshFactory.CreateScreenQuad(_device);

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

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

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


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

            OnInitialize();
            CreateBuffers();
            SetSceneConstants();
        }
Exemple #38
0
        internal EffectConstantBuffer GetOrCreateConstantBuffer(GraphicsDevice context, EffectData.ConstantBuffer bufferRaw)
        {
            // Only lock the constant buffer object
            lock (mapNameToConstantBuffer)
            {
                Dictionary<string, Dictionary<EffectConstantBufferKey, EffectConstantBuffer>> nameToConstantBufferList;

                // ----------------------------------------------------------------------------
                // 1) Get the cache of constant buffers for a particular GraphicsDevice
                // ----------------------------------------------------------------------------
                // TODO cache is not clear if a GraphicsDevice context is disposed
                // To simplify, we assume that a GraphicsDevice is alive during the whole life of the application.
                if (!mapNameToConstantBuffer.TryGetValue(context, out nameToConstantBufferList))
                {
                    nameToConstantBufferList = new Dictionary<string, Dictionary<EffectConstantBufferKey, EffectConstantBuffer>>();
                    mapNameToConstantBuffer[context] = nameToConstantBufferList;
                }

                // ----------------------------------------------------------------------------
                // 2) Get a set of constant buffers for a particular constant buffer name
                // ----------------------------------------------------------------------------
                Dictionary<EffectConstantBufferKey, EffectConstantBuffer> bufferSet;
                if (!nameToConstantBufferList.TryGetValue(bufferRaw.Name, out bufferSet))
                {
                    bufferSet = new Dictionary<EffectConstantBufferKey, EffectConstantBuffer>();
                    nameToConstantBufferList[bufferRaw.Name] = bufferSet;
                }

                // ----------------------------------------------------------------------------
                // 3) Get an existing constant buffer having the same name/size/layout/parameters
                // ----------------------------------------------------------------------------
                var bufferKey = new EffectConstantBufferKey(bufferRaw);
                EffectConstantBuffer buffer;
                if (!bufferSet.TryGetValue(bufferKey, out buffer))
                {
                    // 4) If this buffer doesn't exist, create a new one and register it.
                    buffer = new EffectConstantBuffer(graphicsDevice, bufferRaw);
                    bufferSet[bufferKey] = ToDispose(buffer);
                }

                return buffer;
            }
        }
Exemple #39
0
        protected override void Initialize()
        {
            base.Initialize();

            if (this.Parameters.Contains("blockSampler"))
                this.Parameters["blockSampler"].SetResource(this.GraphicsDevice.SamplerStates.LinearClamp);

            m_perObConstBuf = this.ConstantBuffers["PerObjectBuffer"];
            m_objectWorldMatrixParam = m_perObConstBuf.Parameters["g_chunkOffset"];

            CreateGameColorBuffer();
        }
        private static EffectVariable RetrieveVariableByName(EffectConstantBuffer constantBuffer, string name, bool throwIfNotFound)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");
            if (constantBuffer == null)
                throw new ArgumentNullException("constantBuffer");

            EffectVariable variable = constantBuffer.GetMemberByName(name);
            if (!variable.IsValid && throwIfNotFound)
                throw new ArgumentException(string.Format("Can't retrieve variable with given name {0}.", name), "name");
            return variable;
        }
        private static EffectVariable RetrieveVariableBySemantic(EffectConstantBuffer constantBuffer, string semantic, bool throwIfNotFound)
        {
            if (constantBuffer == null)
                throw new ArgumentNullException("constantBuffer");
            if (String.IsNullOrEmpty(semantic))
                throw new ArgumentNullException("semantic");

            EffectVariable variable = constantBuffer.GetMemberBySemantic(semantic);
            if (!variable.IsValid && throwIfNotFound)
                throw new ArgumentException(string.Format("Can't retrieve variable with given semantic {0}.", semantic), "semantic");
            return variable;
        }
Exemple #42
0
        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();
        }
Exemple #43
0
        /// <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;
        }
Exemple #44
0
 public ConstantBufferLink(EffectConstantBuffer constantBuffer, EffectParameter parameter)
 {
     ConstantBuffer = constantBuffer;
     Parameter = parameter;
     ResourceIndex = 0;
 }
Exemple #45
0
        protected override void Initialize()
        {
            base.Initialize();

            this.Parameters["g_sampler"].SetResource(this.GraphicsDevice.SamplerStates.LinearClamp);

            m_perObConstBuf = this.ConstantBuffers["PerObjectBuffer"];
            m_objectWorldMatrixParam = m_perObConstBuf.Parameters["g_chunkOffset"];
        }