예제 #1
0
        public static string FindPassAnnotationString(Effect effect, EffectHandle handle, string name)
        {
            if (effect == null)
            {
                throw new ArgumentNullException(nameof(effect));
            }
            if (handle == null)
            {
                throw new ArgumentNullException(nameof(handle));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            PassDescription paramDesc = effect.GetPassDescription(handle);

            for (int i = 0; i < paramDesc.Annotations; i++)
            {
                EffectHandle annotationHandle = effect.GetAnnotation(handle, i);
                if (annotationHandle != null)
                {
                    ParameterDescription annotationDesc = effect.GetParameterDescription(annotationHandle);
                    if (annotationDesc.Type == ParameterType.String && StringUtils.EqualsIgnoreCase(annotationDesc.Name, name))
                    {
                        return(effect.GetString(annotationHandle));
                    }
                }
            }
            return(null);
        }
예제 #2
0
        private void InitializeGeometryBuffers()
        {
            PassDescription PassDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayouts,
                PassDesc.InputAssemblerInputSignature,
                PassDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.InputLayout = vertexLayout;


            BufferDescription bd = new BufferDescription();

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(vertexArray.s_VertexArray);
            bd.BindingOptions               = BindingOptions.VertexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(vertexArray.s_VertexArray));

            Marshal.StructureToPtr(vertexArray.s_VertexArray, ptr, true);
            SubresourceData initData = new SubresourceData {
                SystemMemory = ptr
            };

            vertexBuffer = device.CreateBuffer(bd, initData);
            Marshal.FreeHGlobal(ptr);

            // Set vertex buffer
            uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0, // StartSlot
                new[] { vertexBuffer },
                new[] { stride },
                new[] { offset });

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(vertexArray.s_FacesIndexArray);
            bd.BindingOptions               = BindingOptions.IndexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            ptr = Marshal.AllocHGlobal(Marshal.SizeOf(vertexArray.s_FacesIndexArray));
            Marshal.StructureToPtr(vertexArray.s_FacesIndexArray, ptr, true);

            initData.SystemMemory = ptr;
            facesIndexBuffer      = device.CreateBuffer(bd, initData);

            // Set primitive topology
            device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;
        }
예제 #3
0
        internal ShaderPass(DeviceContext context, Shader shader, EffectHandle passHandle, int index)
        {
            Shader  = shader;
            Effect  = shader.Effect;
            Handle  = passHandle;            // TODO: Correct assignment, or reserved for a different handle?
            Context = context;
            Index   = index;

            PassDescription desc = shader.Effect.GetPassDescription(passHandle);

            Name = desc.Name;
        }
        private void InitVertexLayout()
        {
            // Define the input layout
            // The layout determines the stride in the vertex buffer,
            // so changes in layout need to be reflected in SetVertexBuffers
            InputElementDescription[] layout =
            {
                new InputElementDescription()
                {
                    SemanticName         = "POSITION",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32B32Float,
                    InputSlot            = 0,
                    AlignedByteOffset    = 0,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
                new InputElementDescription()
                {
                    SemanticName         = "TEXCOORD",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32Float,
                    InputSlot            = 0,
                    AlignedByteOffset    = 12,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                },
            };

            PassDescription passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                layout,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize);

            device.IA.InputLayout = vertexLayout;
        }
예제 #5
0
        void CreateDeviceResources()
        {
            uint width = (uint) host.ActualWidth;
            uint height = (uint) host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            DXGIFactory dxgiFactory = DXGIFactory.CreateFactory();

            SwapChainDescription swapDesc = new SwapChainDescription();
            swapDesc.BufferDescription.Width = width;
            swapDesc.BufferDescription.Height = height;
            swapDesc.BufferDescription.Format = Format.R8G8B8A8_UNORM;
            swapDesc.BufferDescription.RefreshRate.Numerator = 60;
            swapDesc.BufferDescription.RefreshRate.Denominator = 1;
            swapDesc.SampleDescription.Count = 1;
            swapDesc.SampleDescription.Quality = 0;
            swapDesc.BufferUsage = UsageOption.RenderTargetOutput;
            swapDesc.BufferCount = 1;
            swapDesc.OutputWindowHandle = host.Handle;
            swapDesc.Windowed = true;

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();
            rsDesc.AntialiasedLineEnable = false;
            rsDesc.CullMode = CullMode.None;
            rsDesc.DepthBias = 0;
            rsDesc.DepthBiasClamp = 0;
            rsDesc.DepthClipEnable = true;
            rsDesc.FillMode = D3D10.FillMode.Solid;
            rsDesc.FrontCounterClockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable = false;
            rsDesc.ScissorEnable = false;
            rsDesc.SlopeScaledDepthBias = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.SetState(
                rasterizerState
                );

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.SetRenderTargets(new RenderTargetView[] {null});

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();
            renderDesc.Format = Format.R8G8B8A8_UNORM;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;
            renderDesc.Texture2D.MipSlice = 0;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer<D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.SetRenderTargets(new RenderTargetView[] {renderTargetView}, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsage.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription;
            tex2DDescription.ArraySize = 1;
            tex2DDescription.BindFlags = BindFlag.RenderTarget | BindFlag.ShaderResource;
            tex2DDescription.CpuAccessFlags = CpuAccessFlag.Unspecified;
            tex2DDescription.Format = Format.R8G8B8A8_UNORM;
            tex2DDescription.Height = 4096;
            tex2DDescription.Width = 512;
            tex2DDescription.MipLevels = 1;
            tex2DDescription.MiscFlags = 0;
            tex2DDescription.SampleDescription.Count = 1;
            tex2DDescription.SampleDescription.Quality = 0;
            tex2DDescription.Usage = Usage.Default;

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GetDXGISurface())
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateDxgiSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8_UNORM, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool: 
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable = shader.GetVariableByName("World").AsMatrix();
            viewMatrixVariable = shader.GetVariableByName("View").AsMatrix();
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix();
            diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource();

            // Create the input layout
            PassDescription passDesc = new PassDescription();
            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.SetInputLayout(
                vertexLayout
                );

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));
            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();
            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindFlags = BindFlag.VertexBuffer;
            bd.CpuAccessFlags = CpuAccessFlag.Unspecified;
            bd.MiscFlags = ResourceMiscFlag.Undefined;

            SubresourceData InitData = new SubresourceData()
                                           {
                                               SysMem = verticesDataPtr
                                           };


            vertexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint) Marshal.SizeOf(typeof (SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] {vertexBuffer},
                new uint[] {stride},
                new uint[] {offset}
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));
            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage = Usage.Default;
            bd.ByteWidth = (uint) Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindFlags = BindFlag.IndexBuffer;
            bd.CpuAccessFlags = 0;
            bd.MiscFlags = 0;

            InitData.SysMem = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.SetPrimitiveTopology(PrimitiveTopology.TriangleList);

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float) Math.PI*0.1f,
                width/(float) height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
                {
                    new GradientStop(0.0f, new ColorF(Colors.Yellow)),
                    new GradientStop(1.0f, new ColorF(Colors.Black))
                };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops,
                Gamma.Gamma_22,
                ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
예제 #6
0
        public async Task <AdminResponse> UpdatePass(PassInformationViewModel passInformation)
        {
            _logger.LogInfo("Trying to update existing pass information");
            try
            {
                _logger.LogInfo("Trying to update existing pass information");
                //Get Existing Pass info based on Pass
                PassInformation passInfo = await this._passRepository.GetActivePass(passInformation.Id);

                //If null then throw exception with invalid information
                if (passInfo == null)
                {
                    return(new AdminResponse(false, string.Format(_messageHandler.GetMessage(ErrorMessagesEnum.InValidPassDescription))));
                }

                PassDescription passDesc = new PassDescription();
                //if null then update only Pass information otherwise update Pass description
                if (passInformation.PassDescription != null && passInformation.PassDescription.Count() > 0)
                {
                    //Get Existing Pass desc based on Pass desc id
                    passDesc = passInfo.PassDescription?.Where(p => p.Id == passInformation.PassDescription.FirstOrDefault().Id&& p.SelectedLanguage == passInformation.PassDescription.FirstOrDefault().SelectedLanguage&& p.IsActive).FirstOrDefault();

                    //Pass remain active whole day(ex: 10/29/2019 23:59:59)
                    passInformation.PassExpiredDate = passInformation.PassExpiredDate.AddDays(1).AddSeconds(-1);

                    ////mapped view model to entity
                    passInfo = _mapper.Map <PassInformation>(passInformation);

                    //If null then add new Pass desc with selected language otherwise update existing Pass desc.
                    if (passDesc != null)
                    {
                        //update existing entity from edited by user
                        passDesc = passInfo.PassDescription.FirstOrDefault();

                        //Updated Pass information
                        _passRepository.UpdatePass(passInfo);
                        _logger.LogInfo("Successfully updated Pass information");

                        //Updated pass description
                        _passDescriptionRepository.UpdatePassDesc(passDesc);
                        _logger.LogInfo("Successfully updated Pass Description information");

                        //If selected Pass has already been added then remove all assigned pass along with PTO information from mapper table
                        _passActivePTOMapper.BulkDeletePass(passInfo.Id);
                        _logger.LogInfo("Removed all assigned PTOs with Pass information from mapper table");

                        //Add new updated PTOs for a pass information in Mapper table
                        _passActivePTOMapper.BulkAddPTO(passInfo.PassActivePTOs.ToArray());
                        _logger.LogInfo("Successfully added PTOs information in mapper table");
                    }
                    else
                    {
                        //Added new Pass description if new language selected by user
                        _passDescriptionRepository.AddPassDesc(passInfo.PassDescription.FirstOrDefault());
                        _logger.LogInfo("Successfully added Pass description information");
                    }
                }
                else
                {
                    return(new AdminResponse(false, string.Format(_messageHandler.GetMessage(ErrorMessagesEnum.InValidPassDescription))));
                }

                AdminResponse response = new AdminResponse(true, "Successfully saved");
                response.PassInformation = passInformation;
                return(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(new AdminResponse(false, ex.Message));
            }
        }
예제 #7
0
        private void RenderPart(Part part, Matrix3D parentMatrix, ShaderResourceView parentTextureOverride)
        {
            // set part transform
            Transform3DGroup partGroup = new Transform3DGroup();

            partGroup.Children.Add(new MatrixTransform3D(PartAnimation(part.name)));
            partGroup.Children.Add(new MatrixTransform3D(part.partTransform.ToMatrix3D()));
            partGroup.Children.Add(new MatrixTransform3D(parentMatrix));

            parentMatrix = partGroup.Value;

            ShaderResourceView textureOverride = UpdateRasterizerStateForPart(part);

            if (textureOverride == null)
            {
                textureOverride = parentTextureOverride;
            }
            else
            {
                parentTextureOverride = textureOverride;
            }

            if (part.vertexBuffer != null)
            {
                EffectTechnique technique;

                if (textureOverride != null)
                {
                    technique = this.manager.techniqueRenderTexture;
                    this.manager.diffuseVariable.Resource = textureOverride;
                }
                else if (part.material == null)
                {
                    technique = this.manager.techniqueRenderVertexColor;
                }
                else
                {
                    if (part.material.textureResource != null)
                    {
                        technique = this.manager.techniqueRenderTexture;
                        this.manager.diffuseVariable.Resource = part.material.textureResource;
                    }
                    else
                    {
                        technique = this.manager.techniqueRenderMaterialColor;
                        this.manager.materialColorVariable.FloatVector = part.material.materialColor;
                    }
                }

                this.manager.worldVariable.Matrix = parentMatrix.ToMatrix4x4F();

                //set up vertex buffer and index buffer
                uint stride = (uint)Marshal.SizeOf(typeof(XMeshVertex));
                uint offset = 0;
                this.manager.device.IA.SetVertexBuffers(0, new D3DBuffer[]
                                                        { part.vertexBuffer },
                                                        new uint[] { stride },
                                                        new uint[] { offset });

                //Set primitive topology
                this.manager.device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;

                TechniqueDescription techDesc = technique.Description;
                for (uint p = 0; p < techDesc.Passes; ++p)
                {
                    technique.GetPassByIndex(p).Apply();
                    PassDescription passDescription = technique.GetPassByIndex(p).Description;

                    using (InputLayout inputLayout = this.manager.device.CreateInputLayout(
                               part.dataDescription,
                               passDescription.InputAssemblerInputSignature,
                               passDescription.InputAssemblerInputSignatureSize))
                    {
                        // set vertex layout
                        this.manager.device.IA.InputLayout = inputLayout;

                        // draw part
                        this.manager.device.Draw((uint)part.vertexCount, 0);

                        // Note: In Direct3D 10, the device will not retain a reference
                        // to the input layout, so it's important to reset the device's
                        // input layout before disposing the object.  Were this code
                        // using Direct3D 11, the device would in fact retain a reference
                        // and so it would be safe to go ahead and dispose the input
                        // layout without resetting it; in that case, there could be just
                        // a single assignment to null outside the 'for' loop, or even
                        // no assignment at all.
                        this.manager.device.IA.InputLayout = null;
                    }
                }
            }

            foreach (Part childPart in part.parts)
            {
                RenderPart(childPart, parentMatrix, parentTextureOverride);
            }
        }
예제 #8
0
        void CreateDeviceResources()
        {
            uint width  = (uint)host.ActualWidth;
            uint height = (uint)host.ActualHeight;

            // If we don't have a device, need to create one now and all
            // accompanying D3D resources.
            CreateDevice();

            Factory dxgiFactory = Factory.Create();

            SwapChainDescription swapDesc = new SwapChainDescription
            {
                BufferDescription = new ModeDescription
                {
                    Width       = width, Height = height,
                    Format      = Format.R8G8B8A8UNorm,
                    RefreshRate = new Rational {
                        Numerator = 60, Denominator = 1
                    }
                },
                SampleDescription = new SampleDescription {
                    Count = 1, Quality = 0
                },
                BufferUsage        = UsageOptions.RenderTargetOutput,
                BufferCount        = 1,
                OutputWindowHandle = host.Handle,
                Windowed           = true
            };

            swapChain = dxgiFactory.CreateSwapChain(
                device, swapDesc);

            // Create rasterizer state object
            RasterizerDescription rsDesc = new RasterizerDescription();

            rsDesc.AntiAliasedLineEnable = false;
            rsDesc.CullMode              = CullMode.None;
            rsDesc.DepthBias             = 0;
            rsDesc.DepthBiasClamp        = 0;
            rsDesc.DepthClipEnable       = true;
            rsDesc.FillMode              = D3D10.FillMode.Solid;
            rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9
            rsDesc.MultisampleEnable     = false;
            rsDesc.ScissorEnable         = false;
            rsDesc.SlopeScaledDepthBias  = 0;

            rasterizerState = device.CreateRasterizerState(
                rsDesc);

            device.RS.State = rasterizerState;

            // If we don't have a D2D render target, need to create all of the resources
            // required to render to one here.
            // Ensure that nobody is holding onto one of the old resources
            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null });

            InitializeDepthStencil(width, height);

            // Create views on the RT buffers and set them on the device
            RenderTargetViewDescription renderDesc = new RenderTargetViewDescription();

            renderDesc.Format        = Format.R8G8B8A8UNorm;
            renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D;

            Texture2DRenderTargetView renderView = renderDesc.Texture2D;

            renderView.MipSlice  = 0;
            renderDesc.Texture2D = renderView;

            using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0))
            {
                renderTargetView = device.CreateRenderTargetView(
                    spBackBufferResource,
                    renderDesc);
            }

            device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView);

            SetViewport(width, height);


            // Create a D2D render target which can draw into the surface in the swap chain
            RenderTargetProperties props =
                new RenderTargetProperties(
                    RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
                    96, 96, RenderTargetUsages.None, FeatureLevel.Default);

            // Allocate a offscreen D3D surface for D2D to render our 2D content into
            Texture2DDescription tex2DDescription = new Texture2DDescription
            {
                ArraySize                    = 1,
                BindingOptions               = BindingOptions.RenderTarget | BindingOptions.ShaderResource,
                CpuAccessOptions             = CpuAccessOptions.None,
                Format                       = Format.R8G8B8A8UNorm,
                Height                       = 4096,
                Width                        = 512,
                MipLevels                    = 1,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None,
                SampleDescription            = new SampleDescription {
                    Count = 1, Quality = 0
                },
                Usage = Usage.Default
            };

            offscreenTexture = device.CreateTexture2D(tex2DDescription);

            using (Surface dxgiSurface = offscreenTexture.GraphicsSurface)
            {
                // Create a D2D render target which can draw into our offscreen D3D surface
                renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget(
                    dxgiSurface,
                    props);
            }

            PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied);

            opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None,
                                                                            alphaOnlyFormat);

            // Load pixel shader
            // Open precompiled vertex shader
            // This file was compiled using DirectX's SDK Shader compilation tool:
            // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx
            shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo");

            // Obtain the technique
            technique = shader.GetTechniqueByName("Render");

            // Obtain the variables
            worldMatrixVariable     = shader.GetVariableByName("World").AsMatrix;
            viewMatrixVariable      = shader.GetVariableByName("View").AsMatrix;
            projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix;
            diffuseVariable         = shader.GetVariableByName("txDiffuse").AsShaderResource;

            // Create the input layout
            PassDescription passDesc = new PassDescription();

            passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                inputLayoutDescriptions,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize
                );

            // Set the input layout
            device.IA.InputLayout = vertexLayout;

            IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance));

            Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true);

            BufferDescription bd = new BufferDescription();

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.VerticesInstance);
            bd.BindingOptions               = BindingOptions.VertexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            SubresourceData InitData = new SubresourceData {
                SystemMemory = verticesDataPtr
            };

            vertexBuffer = device.CreateBuffer(bd, InitData);

            Marshal.FreeHGlobal(verticesDataPtr);

            // Set vertex buffer
            uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex));
            uint offset = 0;

            device.IA.SetVertexBuffers(
                0,
                new D3DBuffer[] { vertexBuffer },
                new uint[] { stride },
                new uint[] { offset }
                );

            IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance));

            Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true);

            bd.Usage                        = Usage.Default;
            bd.ByteWidth                    = (uint)Marshal.SizeOf(VertexArray.IndicesInstance);
            bd.BindingOptions               = BindingOptions.IndexBuffer;
            bd.CpuAccessOptions             = CpuAccessOptions.None;
            bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;

            InitData.SystemMemory = indicesDataPtr;

            facesIndexBuffer = device.CreateBuffer(
                bd,
                InitData
                );

            Marshal.FreeHGlobal(indicesDataPtr);

            // Set primitive topology
            device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;

            // Convert the D2D texture into a Shader Resource View
            textureResourceView = device.CreateShaderResourceView(
                offscreenTexture);

            // Initialize the world matrices
            worldMatrix = Matrix4x4F.Identity;

            // Initialize the view matrix
            Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f);
            Vector3F At  = new Vector3F(0.0f, -3.5f, 45.0f);
            Vector3F Up  = new Vector3F(0.0f, 1.0f, 0.0f);

            viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up);

            // Initialize the projection matrix
            projectionMatrix = Camera.MatrixPerspectiveFovLH(
                (float)Math.PI * 0.1f,
                width / (float)height,
                0.1f,
                100.0f);

            // Update Variables that never change
            viewMatrixVariable.Matrix = viewMatrix;

            projectionMarixVariable.Matrix = projectionMatrix;

            GradientStop[] gradientStops =
            {
                new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))),
                new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black)))
            };

            GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection(
                gradientStops, Gamma.StandardRgb, ExtendMode.Clamp);

            // Create a linear gradient brush for text
            textBrush = renderTarget.CreateLinearGradientBrush(
                new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)),
                spGradientStopCollection
                );
        }
예제 #9
0
        /// <summary>
        /// Create Direct3D device and swap chain
        /// </summary>
        protected void InitDevice()
        {
            device    = D3DDevice.CreateDeviceAndSwapChain(directControl.Handle);
            swapChain = device.SwapChain;

            SetViews();

            // Create the effect
            using (FileStream effectStream = File.OpenRead("Tutorial02.fxo"))
            {
                effect = device.CreateEffectFromCompiledBinary(new BinaryReader(effectStream));
            }

            // Obtain the technique
            technique = effect.GetTechniqueByName("Render");

            // Define the input layout
            InputElementDescription[] layout =
            {
                new InputElementDescription()
                {
                    SemanticName         = "POSITION",
                    SemanticIndex        = 0,
                    Format               = Format.R32G32B32Float,
                    InputSlot            = 0,
                    AlignedByteOffset    = 0,
                    InputSlotClass       = InputClassification.PerVertexData,
                    InstanceDataStepRate = 0
                }
            };

            PassDescription passDesc = technique.GetPassByIndex(0).Description;

            vertexLayout = device.CreateInputLayout(
                layout,
                passDesc.InputAssemblerInputSignature,
                passDesc.InputAssemblerInputSignatureSize);

            device.IA.InputLayout = vertexLayout;

            SimpleVertexArray vertex = new SimpleVertexArray();

            BufferDescription bd = new BufferDescription()
            {
                Usage                        = Usage.Default,
                ByteWidth                    = (uint)Marshal.SizeOf(vertex),
                BindingOptions               = BindingOptions.VertexBuffer,
                CpuAccessOptions             = CpuAccessOptions.None,
                MiscellaneousResourceOptions = MiscellaneousResourceOptions.None
            };

            IntPtr vertexData = Marshal.AllocCoTaskMem(Marshal.SizeOf(vertex));

            Marshal.StructureToPtr(vertex, vertexData, false);

            SubresourceData InitData = new SubresourceData()
            {
                SystemMemory           = vertexData,
                SystemMemoryPitch      = 0,
                SystemMemorySlicePitch = 0
            };

            //D3DBuffer buffer = null;
            vertexBuffer = device.CreateBuffer(bd, InitData);

            // Set vertex buffer
            uint stride = (uint)Marshal.SizeOf(typeof(Vector3F));
            uint offset = 0;

            device.IA.SetVertexBuffers(0, new Collection <D3DBuffer>()
            {
                vertexBuffer
            },
                                       new uint[] { stride }, new uint[] { offset });

            // Set primitive topology
            device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList;
            Marshal.FreeCoTaskMem(vertexData);
        }