protected virtual void OnInitializeDevice() { Form.ClientSize = new System.Drawing.Size(Width, Height); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = Form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out _device, out _swapChain); outputMerger = _device.OutputMerger; inputAssembler = _device.InputAssembler; Factory factory = _swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(Form.Handle, WindowAssociationFlags.None); }
// Used with soft bodies public void SetDynamicVertexBuffer(Device device, Vector3[] vectors) { if (VertexBuffer != null && VertexCount * 2 == vectors.Length) { // Update existing buffer using (var data = VertexBuffer.Map(MapMode.WriteDiscard)) { data.WriteRange(vectors, 0, vectors.Length); VertexBuffer.Unmap(); } } else { // Create new buffer if (VertexBuffer != null) VertexBuffer.Dispose(); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vectors.Length, Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); } }
/* * public void RenderSoftBodyTextured(SoftBody softBody) * { * if (!(softBody.UserObject is Array)) * return; * * object[] userObjArr = softBody.UserObject as object[]; * FloatArray vertexBuffer = userObjArr[0] as FloatArray; * IntArray indexBuffer = userObjArr[1] as IntArray; * * int vertexCount = (vertexBuffer.Count / 8); * * if (vertexCount > 0) * { * int faceCount = indexBuffer.Count / 2; * * bool index32 = vertexCount > 65536; * * Mesh mesh = new Mesh(device, faceCount, vertexCount, * MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), * VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1); * * SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard); * if (index32) * { * foreach (int i in indexBuffer) * indices.Write(i); * } * else * { * foreach (int i in indexBuffer) * indices.Write((ushort)i); * } * mesh.UnlockIndexBuffer(); * * SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard); * foreach (float f in vertexBuffer) * verts.Write(f); * mesh.UnlockVertexBuffer(); * * mesh.ComputeNormals(); * mesh.DrawSubset(0); * mesh.Dispose(); * } * } * */ public static Buffer CreateScreenQuad(Device device) { Buffer vertexBuffer; BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(float) * 5 * 4, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.Write(new Vector3(0.5f, 0.5f, 0)); data.Write(new Vector2(1, 0)); data.Write(new Vector3(0.5f, -0.5f, 0)); data.Write(new Vector2(1, 1)); data.Write(new Vector3(-0.5f, 0.5f, 0)); data.Write(new Vector2(0, 0)); data.Write(new Vector3(-0.5f, -0.5f, 0)); data.Write(new Vector2(0, 1)); data.Position = 0; vertexBuffer = new Buffer(device, data, vertexBufferDesc); } return(vertexBuffer); }
private void DrawPositionNormalColorIndexedTriangleBuffer(Device device, VertexAndIndexDeviceBuffer deviceBuffers, Matrix worldViewProj) { int layoutNumber = 4; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; if (null != deviceBuffers.ClipPlanes) { for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(deviceBuffers.ClipPlanes[i]); } } SetShaderMaterialVariables(deviceBuffers.Material); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 48, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].Pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); if (null != deviceBuffers.ClipPlanes) { var emptyPlane = new Plane(); for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(emptyPlane); } } }
public CompositionDevice(Adapter1 adapter, Device2D device2D) { Contract.Requires(device2D != null); _DxgiFactory = new Lazy<Factory1>(); Adapter1 newAdapter = adapter; if(adapter == null) { newAdapter = _DxgiFactory.Value.GetAdapter1(0); } #if DEBUG _Device3D = new Device1( newAdapter, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug, FeatureLevel.Level_10_0); #else _Device3D = new Device1( newAdapter, DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); #endif if(adapter == null) { newAdapter.Dispose(); } _Compositor = new Compositor(_Device3D, device2D); device2D.Resources.RegisterEffect<ColorOutputEffect>(); device2D.Resources.RegisterEffect<GaussianBlurEffect>(); device2D.Resources.RegisterEffect<DropShadowEffect>(); device2D.Resources.RegisterEffect<BoxBlurEffect>(); }
void IScene.Render() { Device device = this.Host.Device; if (device == null) { return; } device.InputAssembler.InputLayout = this.VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.Vertices, 32, 0)); device.InputAssembler.SetIndexBuffer(Indices, Format.R32_UInt, 0); device.Rasterizer.SetViewports(viewport); EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); //EffectVectorVariable overlayColor = this.SimpleEffect.GetVariableBySemantic("OverlayColor").AsVector(); //overlayColor.Set(this.OverlayColor); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); for (int j = 0; j < nrTextures; j++) { device.PixelShader.SetShaderResource(j, textureView[j]); } device.DrawIndexed(nrIndices, 0, 0); } }
public MeshFactory(SharpDXGraphics graphics) { this.device = graphics.Device; this.inputAssembler = device.InputAssembler; this.demo = graphics.Demo; instanceDataDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }; InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("WORLD", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 64, 1, InputClassification.PerInstanceData, 1) }; inputLayout = new InputLayout(device, graphics.GetEffectPass().Description.Signature, elements); groundColor = ColorToUint(Color.Green); activeColor = ColorToUint(Color.Orange); passiveColor = ColorToUint(Color.OrangeRed); softBodyColor = ColorToUint(Color.LightBlue); }
public InfoText(Device device) { this.device = device; outputMerger = device.OutputMerger; font = new Font(device, 20, 0, FontWeight.Normal, 0, false, FontCharacterSet.Default, FontPrecision.Default, FontQuality.ClearTypeNatural, FontPitchAndFamily.DontCare, "tahoma"); renderTexture = new Texture2D(device, new Texture2DDescription() { ArraySize = 1, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, Format = Format.R8G8B8A8_UNorm, Height = rect.Height, Width = rect.Width, MipLevels = 1, OptionFlags = ResourceOptionFlags.None, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default }); renderTextureView = new RenderTargetView(device, renderTexture); renderViews = new[] { renderTextureView }; OverlayBufferRes = new ShaderResourceView(device, renderTexture, new ShaderResourceViewDescription() { Format = Format.R8G8B8A8_UNorm, Dimension = ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource() { MipLevels = 1, MostDetailedMip = 0 } }); }
void IScene.Render() { Device device = this.Host.Device; if (device == null) { return; } device.InputAssembler.InputLayout = this.VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(this.Vertices, 32, 0)); EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); EffectVectorVariable overlayColor = this.SimpleEffect.GetVariableBySemantic("OverlayColor").AsVector(); overlayColor.Set(this.OverlayColor); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); device.Draw(3, 0); } }
private void BringOverlayGeometryIntoDeviceBuffers(D3D10OverlayContext overlayGeometry) { Device device = _cachedDevice; if (device == null || device.IsDisposed) { return; } // ------------------ Triangle buffer ------------------------------------ { var buf = (PositionColorIndexedTriangleBuffer)overlayGeometry.PositionColorIndexedTriangleBuffers; var vertexBuffer = Buffer.Create <float>(device, buf.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.VertexStreamLength, Usage = ResourceUsage.Default }); var indexBuffer = Buffer.Create <int>(device, buf.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.IndexStreamLength, Usage = ResourceUsage.Default }); var indexCount = buf.TriangleCount * 3; var oldBuffer = System.Threading.Interlocked.Exchange( ref _overlayGeometryTriangleDeviceBuffer, new VertexAndIndexDeviceBufferNoMaterial(vertexBuffer: vertexBuffer, vertexCount: buf.VertexCount, indexBuffer: indexBuffer, indexCount: indexCount)); Disposer.RemoveAndDispose(ref oldBuffer); } // ------------------ Line list buffer ------------------------------------ { var buf = (PositionColorLineListBuffer)overlayGeometry.PositionColorLineListBuffer; var vertexBuffer = Buffer.Create <float>(device, buf.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = buf.VertexStreamLength, Usage = ResourceUsage.Default }); var oldBuffer = System.Threading.Interlocked.Exchange( ref _overlayGeometryLineListBuffer, new VertexBufferNoMaterial(vertexBuffer: vertexBuffer, vertexCount: buf.VertexCount)); oldBuffer?.Dispose(); } }
public override void Hook() { DebugMessage("Hook: Begin"); // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain if (_d3d10VTblAddresses == null) { _d3d10VTblAddresses = new List <IntPtr>(); _dxgiSwapChainVTblAddresses = new List <IntPtr>(); DebugMessage("Hook: Before device creation"); using (var factory = new Factory()) { using (var device = new Device(factory.GetAdapter(0), DeviceCreationFlags.None)) { DebugMessage("Hook: Device created"); _d3d10VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_DEVICE_METHOD_COUNT)); using (var renderForm = new Form()) { using ( var sc = new SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle))) { _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT)); } } } } } // We will capture the backbuffer here DXGISwapChain_PresentHook = new Hook <DXGISwapChain_PresentDelegate>( _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.Present], new DXGISwapChain_PresentDelegate(PresentHook), this); // We will capture target/window resizes here DXGISwapChain_ResizeTargetHook = new Hook <DXGISwapChain_ResizeTargetDelegate>( _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.ResizeTarget], new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook), this); /* * Don't forget that all hooks will start deactivated... * The following ensures that all threads are intercepted: * Note: you must do this for each hook. */ DXGISwapChain_PresentHook.Activate(); DXGISwapChain_ResizeTargetHook.Activate(); Hooks.Add(DXGISwapChain_PresentHook); Hooks.Add(DXGISwapChain_ResizeTargetHook); }
private void DrawPositionColorLineListBufferNoMaterial(Device device, VertexBufferNoMaterial deviceBuffers, Matrix worldViewProj) { int layoutNumber = 1; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, (8 * 4), 0)); _renderLayouts[layoutNumber].Pass.Apply(); device.Draw(deviceBuffers.VertexCount, 0); }
private void DrawPositionColorIndexedTriangleBufferNoMaterial(Device device, VertexAndIndexDeviceBufferNoMaterial deviceBuffers, Matrix worldViewProj) { int layoutNumber = 1; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 32, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].Pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); }
/// <summary> /// /// </summary> /// <param name="dev"></param> public D3D10(Device dev) { if (dev != null) { //dev.AddReference(); this.m_device = dev; } else { m_device = DeviceUtil.Create10(DeviceCreationFlags.BgraSupport); if (m_device == null) { throw new NotSupportedException(); } } }
void videoPanelViewModel_VideoOpened(Object sender, EventArgs e) { for (int i = 0; i < nrTextures; i++) { Disposer.RemoveAndDispose(ref this.yuvTexture[i]); Disposer.RemoveAndDispose(ref this.textureView[i]); } if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P) { int width = videoPlayerViewModel.Width; int height = videoPlayerViewModel.Height; yuvTexture[0] = createTexture(width, height, Format.R8_UNorm); yuvTexture[1] = createTexture(width / 2, height / 2, Format.R8_UNorm); yuvTexture[2] = createTexture(width / 2, height / 2, Format.R8_UNorm); nrTextures = 3; } else { yuvTexture[0] = createTexture(videoPlayerViewModel.Width, videoPlayerViewModel.Height, Format.B8G8R8A8_UNorm); nrTextures = 1; } Device device = Host.Device; for (int i = 0; i < nrTextures; i++) { ShaderResourceViewDescription desc = new ShaderResourceViewDescription(); desc.Format = yuvTexture[i].Description.Format; desc.Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D; desc.Texture2D.MipLevels = yuvTexture[i].Description.MipLevels; desc.Texture2D.MostDetailedMip = yuvTexture[i].Description.MipLevels - 1; textureView[i] = new ShaderResourceView(device, yuvTexture[i], desc); } viewport = setupViewport(videoPlayerViewModel.Width, videoPlayerViewModel.Height); device.Flush(); DPFCanvas canvas = (DPFCanvas)Host; canvas.StartRendering(); }
private void DrawPositionNormalUIndexedTriangleBuffer(Device device, VertexAndIndexDeviceBuffer deviceBuffers, Matrix worldViewProj) { int layoutNumber = 6; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; // set clip planes if (null != deviceBuffers.ClipPlanes) { for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(deviceBuffers.ClipPlanes[i]); } } // set UColor texture var stream = _textureFor1DColorProvider.Map(0, MapMode.WriteDiscard, SharpDX.Direct3D10.MapFlags.None); //stream.Seek(0, System.IO.SeekOrigin.Begin); stream.Write(deviceBuffers.UColors, 0, deviceBuffers.UColors.Length); //stream.Close(); _textureFor1DColorProvider.Unmap(0); SetShaderMaterialVariables(deviceBuffers.Material); // note: the material's color must be set to the ColorProviders InvalidColor! // draw now device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 32, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].Pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); // clear clip planes afterwards if (null != deviceBuffers.ClipPlanes) { var emptyPlane = new Plane(); for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(emptyPlane); } } }
public void SetIndexBuffer(Device device, uint[] indices) { IndexFormat = Format.R32_UInt; BufferDescription indexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(uint) * indices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.IndexBuffer }; using (var data = new DataStream(indexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(indices); data.Position = 0; IndexBuffer = new Buffer(device, data, indexBufferDesc); } }
public void SetVertexBuffer(Device device, Vector3[] vectors) { BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * vectors.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) { throw new Exception("Scene host device is null"); } ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile("Simple.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0);; EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = 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) }); this.VertexStream = new DataStream(3 * 32, true, true); this.VertexStream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 3 * 32, Usage = ResourceUsage.Default } ); device.Flush(); }
public void SetVertexBuffer(Device device, Vector3[] vertices) { BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Marshal.SizeOf(typeof(Vector3)) * vertices.Length, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer }; using (var data = new SharpDX.DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vertices); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); VertexBuffer.Unmap(); } BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); }
public PhysicsDebugDraw(SharpDXGraphics graphics) { _device = graphics.Device; _inputAssembler = _device.InputAssembler; InputElement[] elements = { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; _inputLayout = new InputLayout(_device, graphics.GetDebugDrawPass().Description.Signature, elements); _vertexBufferDesc = new BufferDescription { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; _vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); }
public PhysicsDebugDraw(SharpDXGraphics graphics) { device = graphics.Device; inputAssembler = device.InputAssembler; InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 12, 0, InputClassification.PerVertexData, 0) }; inputLayout = new InputLayout(device, graphics.GetDebugDrawPass().Description.Signature, elements); vertexBufferDesc = new BufferDescription() { Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; vertexBufferBinding = new VertexBufferBinding(null, PositionColored.Stride, 0); }
public MeshFactory(Demo demo) { this.demo = demo; this.device = demo.Device; this.inputAssembler = device.InputAssembler; instanceDataDesc = new BufferDescription() { SizeInBytes = 0, Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write, OptionFlags = ResourceOptionFlags.None, }; InputElement[] elements = new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0, InputClassification.PerVertexData, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0, InputClassification.PerVertexData, 0), new InputElement("WORLD", 0, Format.R32G32B32A32_Float, 0, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 1, Format.R32G32B32A32_Float, 16, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 2, Format.R32G32B32A32_Float, 32, 1, InputClassification.PerInstanceData, 1), new InputElement("WORLD", 3, Format.R32G32B32A32_Float, 48, 1, InputClassification.PerInstanceData, 1), new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 64, 1, InputClassification.PerInstanceData, 1) }; inputLayout = new InputLayout(device, demo.GetShadowGenPass().Description.Signature, elements); Color c = Color.Green; groundColor = (uint)c.R + ((uint)c.G << 8) + ((uint)c.B << 16) + ((uint)c.A << 24); c = Color.Orange; activeColor = (uint)c.R + ((uint)c.G << 8) + ((uint)c.B << 16) + ((uint)c.A << 24); c = Color.OrangeRed; passiveColor = (uint)c.R + ((uint)c.G << 8) + ((uint)c.B << 16) + ((uint)c.A << 24); c = Color.LightBlue; softBodyColor = (uint)c.R + ((uint)c.G << 8) + ((uint)c.B << 16) + ((uint)c.A << 24); }
// Used with soft bodies public void SetDynamicVertexBuffer(Device device, Vector3[] vectors) { if (VertexBuffer != null && VertexCount * 2 == vectors.Length) { // Update existing buffer using (var data = VertexBuffer.Map(MapMode.WriteDiscard)) { data.WriteRange(vectors, 0, vectors.Length); VertexBuffer.Unmap(); } } else { // Create new buffer if (VertexBuffer != null) VertexBuffer.Dispose(); BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = Vector3.SizeInBytes * vectors.Length, Usage = ResourceUsage.Dynamic, BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.Write }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.WriteRange(vectors); data.Position = 0; VertexBuffer = new Buffer(device, data, vertexBufferDesc); } VertexCount = vectors.Length / 2; BufferBindings[0] = new VertexBufferBinding(VertexBuffer, 24, 0); } }
private void BringDrawingIntoBuffers(D3D10GraphicsContext altaxoDrawingGeometry) { Device device = _cachedDevice; if (device == null || device.IsDisposed) { return; } var altaxoBuffersOfType = new IEnumerable <KeyValuePair <MaterialKey, IndexedTriangleBuffer> >[] { altaxoDrawingGeometry.PositionIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionColorIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionUVIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalColorIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalUVIndexedTriangleBuffersAsIndexedTriangleBuffers, altaxoDrawingGeometry.PositionNormalUIndexedTriangleBuffersAsIndexedTriangleBuffers }; for (int i = 0; i < altaxoBuffersOfType.Length; ++i) { var newDeviceBuffers = new List <VertexAndIndexDeviceBuffer>(); foreach (var altaxoBuffer in altaxoBuffersOfType[i]) { var altaxoTriangleBuffer = altaxoBuffer.Value; if (altaxoTriangleBuffer.TriangleCount == 0) { continue; } var vertexBuffer = Buffer.Create <float>(device, altaxoTriangleBuffer.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = altaxoTriangleBuffer.VertexStreamLength, Usage = ResourceUsage.Default }); var indexBuffer = Buffer.Create <int>(device, altaxoTriangleBuffer.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = altaxoTriangleBuffer.IndexStreamLength, Usage = ResourceUsage.Default }); var indexCount = altaxoTriangleBuffer.TriangleCount * 3; Plane[] clipPlanes = null; if (altaxoBuffer.Key is MaterialPlusClippingKey) { var axoClipPlanes = ((MaterialPlusClippingKey)altaxoBuffer.Key).ClipPlanes; if (null != axoClipPlanes) { clipPlanes = axoClipPlanes.Select(axoPlane => new Plane((float)axoPlane.X, (float)axoPlane.Y, (float)axoPlane.Z, (float)-axoPlane.W)).ToArray(); } } byte[] uColors = null; var material = altaxoBuffer.Key.Material; if (altaxoTriangleBuffer is PositionNormalUIndexedTriangleBuffer && altaxoBuffer.Key is MaterialPlusClippingPlusColorProviderKey) { var bufs = (PositionNormalUIndexedTriangleBuffer)altaxoTriangleBuffer; var colorProvider = ((MaterialPlusClippingPlusColorProviderKey)(altaxoBuffer.Key)).ColorProvider; var fColors = bufs.GetColorArrayForColorProvider(colorProvider); uColors = new byte[fColors.Length * 4]; System.Buffer.BlockCopy(fColors, 0, uColors, 0, uColors.Length); material = material.WithColor(new NamedColor(colorProvider.GetAxoColor(double.NaN))); // Material needs to have InvalidColor, because this can not be represented in the Texture1D } newDeviceBuffers.Add(new VertexAndIndexDeviceBuffer(material: altaxoBuffer.Key.Material, vertexBuffer: vertexBuffer, vertexCount: altaxoTriangleBuffer.VertexCount, indexBuffer: indexBuffer, indexCount: indexCount, clipPlanes: clipPlanes, uColors: uColors)); } System.Threading.Interlocked.Exchange(ref _nextTriangleDeviceBuffers[i], newDeviceBuffers); } }
void IScene.Render() { Device device = _cachedDevice; if (device == null) { throw new InvalidOperationException("Rendering failed because device is null"); } if (device.IsDisposed) { throw new InvalidOperationException("Rendering failed because device is disposed"); } if (_altaxoCamera == null) { throw new InvalidOperationException("Rendering failed because camera is null"); } if (_altaxoDrawingGeometry == null) { throw new InvalidOperationException("Rendering failed because drawing is null"); } UseNextTriangleDeviceBuffers(); float time = _renderCounter / 100f; ++_renderCounter; Matrix worldViewProjTr; // world-view matrix, transposed if (null != _altaxoCamera) { var cam = _altaxoCamera; var eye = cam.EyePosition; var target = cam.TargetPosition; var up = cam.UpVector; //view = Matrix.LookAtRH(new Vector3((float)eye.X, (float)eye.Y, (float)eye.Z), new Vector3((float)target.X, (float)target.Y, (float)target.Z), new Vector3((float)up.X, (float)up.Y, (float)up.Z)); //var viewProjD3D = (cam as PerspectiveCamera).GetLookAtRHTimesPerspectiveRHMatrix(_hostSize.Y / _hostSize.X); var viewProjD3D = cam.GetViewProjectionMatrix(_hostSize.Y / _hostSize.X); worldViewProjTr = new Matrix( (float)viewProjD3D.M11, (float)viewProjD3D.M21, (float)viewProjD3D.M31, (float)viewProjD3D.M41, (float)viewProjD3D.M12, (float)viewProjD3D.M22, (float)viewProjD3D.M32, (float)viewProjD3D.M42, (float)viewProjD3D.M13, (float)viewProjD3D.M23, (float)viewProjD3D.M33, (float)viewProjD3D.M43, (float)viewProjD3D.M14, (float)viewProjD3D.M24, (float)viewProjD3D.M34, (float)viewProjD3D.M44 ); } else { var view = Matrix.LookAtRH(new Vector3(0, 0, -1500), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovRH((float)Math.PI / 4.0f, (float)(_hostSize.X / _hostSize.Y), 0.1f, float.MaxValue); var viewProj = Matrix.Multiply(view, proj); // Update WorldViewProj Matrix worldViewProjTr = viewProj; worldViewProjTr.Transpose(); } // World projection and camera _evWorldViewProj.SetMatrixTranspose(ref worldViewProjTr); _evEyePosition.Set(ToVector3(_altaxoCamera.EyePosition)); // lighting _lighting.SetLighting(_altaxoLightSettings, _altaxoCamera); // Material is separate for each buffer, therefore it is set there foreach (var entry in _thisTriangleDeviceBuffers[1]) // Position-Color { DrawPositionColorIndexedTriangleBuffer(device, entry, worldViewProjTr); } foreach (var entry in _thisTriangleDeviceBuffers[3]) // Position-Normal { DrawPositionNormalIndexedTriangleBuffer(device, entry, worldViewProjTr); } foreach (var entry in _thisTriangleDeviceBuffers[4]) // Position-Normal-Color { DrawPositionNormalColorIndexedTriangleBuffer(device, entry, worldViewProjTr); } foreach (var entry in _thisTriangleDeviceBuffers[6]) // Position-Normal-U { DrawPositionNormalUIndexedTriangleBuffer(device, entry, worldViewProjTr); } // ------------------ end of document geometry drawing ---------------------------------- // ------------------ start of marker geometry drawing ---------------------------------- var markerTriangles = _markerGeometryTriangleDeviceBuffer; if (null != markerTriangles) { DrawPositionColorIndexedTriangleBufferNoMaterial(device, markerTriangles, worldViewProjTr); } var markerLines = _markerGeometryLineListBuffer; if (null != markerLines && markerLines.VertexCount > 0) { DrawPositionColorLineListBufferNoMaterial(device, markerLines, worldViewProjTr); } // ------------------ end of marker geometry drawing ---------------------------------- // ------------------ start of overlay geometry drawing ---------------------------------- var overlayTriangles = _overlayGeometryTriangleDeviceBuffer; if (null != overlayTriangles) { DrawPositionColorIndexedTriangleBufferNoMaterial(device, overlayTriangles, worldViewProjTr); } var overlayLines = _overlayGeometryLineListBuffer; if (null != overlayLines && overlayLines.VertexCount > 0) { DrawPositionColorLineListBufferNoMaterial(device, overlayLines, worldViewProjTr); } // ------------------ end of overlay geometry drawing ---------------------------------- }
/// <summary> /// /// </summary> /// <param name="args"></param> public override void EndRender(DrawEventArgs args) { Device.Flush(); }
public static BasicHlsl.VertexShaderOutput ExecuteVertexShader(string compiledShaderFile, BasicHlsl.ConstantBufferGlobals globals, VertexPositionNormalTexture vertex) { var device = new Device(DriverType.Warp); var vertexShaderBytes = File.ReadAllBytes(compiledShaderFile); var vertexShaderBytecode = new ShaderBytecode(vertexShaderBytes); var vertexShader = new VertexShader(device, vertexShaderBytecode); var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderBytecode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0) }); var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { vertex }); var constantBuffer = Buffer.Create(device, ref globals, new BufferDescription { BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.None, Usage = ResourceUsage.Default }); var geometryShader = new GeometryShader(device, vertexShaderBytecode, new[] { new StreamOutputElement { SemanticName = "SV_POSITION", ComponentCount = 4 }, new StreamOutputElement { SemanticName = "COLOR", ComponentCount = 4 }, new StreamOutputElement { SemanticName = "TEXCOORD", ComponentCount = 2 } }, BasicHlsl.VertexShaderOutput.SizeInBytes); var outputBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1], new BufferDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.StreamOutput, Usage = ResourceUsage.Default }); var stagingBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1], new BufferDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Usage = ResourceUsage.Staging }); device.InputAssembler.InputLayout = layout; device.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, VertexPositionNormalTexture.SizeInBytes, 0)); device.VertexShader.SetConstantBuffer(0, constantBuffer); device.VertexShader.Set(vertexShader); device.GeometryShader.Set(geometryShader); device.StreamOutput.SetTargets(new StreamOutputBufferBinding(outputBuffer, 0)); device.Draw(1, 0); device.CopyResource(outputBuffer, stagingBuffer); device.Flush(); var stream = stagingBuffer.Map(MapMode.Read, SharpDX.Direct3D10.MapFlags.None); var bytes = new byte[BasicHlsl.VertexShaderOutput.SizeInBytes]; stream.Read(bytes, 0, bytes.Length); stream.Dispose(); outputBuffer.Dispose(); vertices.Dispose(); layout.Dispose(); geometryShader.Dispose(); vertexShader.Dispose(); vertexShaderBytecode.Dispose(); device.Dispose(); return(StructUtility.FromBytes <BasicHlsl.VertexShaderOutput>(bytes)); }
private void DrawPositionColorIndexedTriangleBufferNoMaterial(Device device, VertexAndIndexDeviceBufferNoMaterial deviceBuffers, Matrix worldViewProj) { int layoutNumber = 1; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 32, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); }
//////////////////////////////////////////////////// #region 内部処理の実装 void initializeDirect3D(int backBufferWidth, int backBufferHeight, int surfaceResolutionWidth, int surfaceResolutionHeight, float thetaMappingDepth, double cameraPitchAngle, double cameraOffsetY, double cameraScale, float offsetU) { _width = backBufferWidth; _height = backBufferHeight; //バックバッファのフォーマット Texture2DDescription colordesc = new Texture2DDescription { BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, Format = Format.B8G8R8A8_UNorm, Width = backBufferWidth, Height = backBufferHeight, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.Shared, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1 }; //デプスステンシルのフォーマット //BackBufferと同じサイズで、出力結合ステージで使用 Texture2DDescription depthdesc = new Texture2DDescription { BindFlags = BindFlags.DepthStencil, Format = Format.D32_Float_S8X24_UInt, Width = backBufferWidth, Height = backBufferHeight, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, OptionFlags = ResourceOptionFlags.None, CpuAccessFlags = CpuAccessFlags.None, ArraySize = 1, }; //デバイスの作成 //[TODO]Debug //_device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport | DeviceCreationFlags.Debug); _device = new Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport); //エフェクトの作成 var compileResult = ShaderBytecode.CompileFromFile("Mesh.fx", "fx_4_0", ShaderFlags.OptimizationLevel3, EffectFlags.None, null, null); if (compileResult.HasErrors) { throw new InvalidOperationException("Effect file includes compilation errors. " + compileResult.Message); } _effect = new Effect(_device, compileResult.Bytecode); _effect.GetVariableByName("Transform").AsMatrix().SetMatrix(Matrix.Identity); _technique = _effect.GetTechniqueByName("Mesh"); //頂点レイアウトの設定 var vertexLayout = new InputLayout(_device, _technique.GetPassByIndex(0).Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 12, 0) }); _device.InputAssembler.InputLayout = vertexLayout; _device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; //背景描画用のメッシュの作成 makeSurface(surfaceResolutionWidth, surfaceResolutionHeight); _effect.GetVariableByName("ThetaMappingDepth").AsScalar().Set(thetaMappingDepth); //Barrel Distortion用のテクスチャを作成 _distortion = new Texture2D(_device, colordesc); _distortionView = new RenderTargetView(_device, _distortion); _effect.GetVariableByName("Distortion").AsShaderResource().SetResource(new ShaderResourceView(_device, _distortion)); //オフセット表示用のテクスチャを作成 _offset = new Texture2D(_device, colordesc); _offsetView = new RenderTargetView(_device, _offset); _effect.GetVariableByName("Offset").AsShaderResource().SetResource(new ShaderResourceView(_device, _offset)); _effect.GetVariableByName("OffsetU").AsScalar().Set(offsetU); //描画ターゲットテクスチャの作成 _renderTarget = new Texture2D(_device, colordesc); _renderTargetView = new RenderTargetView(_device, _renderTarget); _depthStencil = new Texture2D(_device, depthdesc); _depthStencilView = new DepthStencilView(_device, _depthStencil); //ImageSourceにRenderTargetを設定 _imageSource.SetRenderTargetDX10(_renderTarget); //Handメッシュの座標変換を設定 var matrix = Matrix3D.Identity; matrix.Rotate(new System.Windows.Media.Media3D.Quaternion(new Vector3D(1, 0, 0), cameraPitchAngle)); matrix.OffsetY = cameraOffsetY; matrix.Scale(new Vector3D(cameraScale, cameraScale, cameraScale)); float[] matValues = { (float)matrix.M11, (float)matrix.M12, (float)matrix.M13, (float)matrix.M14, (float)matrix.M21, (float)matrix.M22, (float)matrix.M23, (float)matrix.M24, (float)matrix.M31, (float)matrix.M32, (float)matrix.M33, (float)matrix.M34, (float)matrix.OffsetX, (float)matrix.OffsetY, (float)matrix.OffsetZ, (float)matrix.M44, }; _effect.GetVariableByName("Transform").AsMatrix().SetMatrix(new Matrix(matValues)); }
private static void Main() { var form = new RenderForm("SharpDX - MiniTri Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); // Ignore all windows events Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer Texture2D backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var effectByteCode = ShaderBytecode.CompileFromFile("MiniTri.fx", "fx_4_0", ShaderFlags.None, EffectFlags.None); var effect = new Effect(device, effectByteCode); var technique = effect.GetTechniqueByIndex(0); var pass = technique.GetPassByIndex(0); // Layout from VertexShader input signature var layout = 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) }); // Write vertex data to a datastream var stream = new DataStream(32 * 3, true, true); stream.WriteRange(new[] { new Vector4(0.0f, 0.5f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-0.5f, -0.5f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f) }); stream.Position = 0; // Instantiate Vertex buiffer from vertex data var vertices = new Buffer(device, stream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = 32 * 3, Usage = ResourceUsage.Default, }); stream.Release(); // Prepare All the stages device.InputAssembler.SetInputLayout(layout); device.InputAssembler.SetPrimitiveTopology(PrimitiveTopology.TriangleList); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, 32, 0)); device.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); device.OutputMerger.SetTargets(renderView); // Main loop RenderLoop.Run(form, () => { device.ClearRenderTargetView(renderView, new Color4(1.0f, 0.0f, 0.0f, 0.0f)); for (int i = 0; i < technique.Description.PassCount; ++i) { pass.Apply(); device.Draw(3, 0); } swapChain.Present(0, PresentFlags.None); }); // Release all resources effectByteCode.Release(); vertices.Release(); layout.Release(); renderView.Release(); backBuffer.Release(); device.ClearState(); device.Flush(); device.Release(); device.Release(); swapChain.Release(); factory.Release(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D 10 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left new Vector4(-1.0f, -1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(-1.0f, 1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), new Vector4(1.0f, 1.0f, 1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf <Vector4>() * 2, 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.OutputMerger.SetTargets(depthView, renderView); context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }
void IScene.Attach(ISceneHost host) { this.Host = host; Device device = host.Device; if (device == null) { throw new Exception("Scene host device is null"); } Uri executablePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); String shaderPath = System.IO.Path.GetDirectoryName(executablePath.LocalPath) + "\\Shaders\\"; if (videoPlayerViewModel.DecodedVideoFormat == VideoLib.VideoPlayer.DecodedVideoFormat.YUV420P) { shaderPath += "YUVtoRGB.fx"; } else { shaderPath += "Simple.fx"; } try { ShaderBytecode shaderBytes = ShaderBytecode.CompileFromFile(shaderPath, "fx_4_0", ShaderFlags.None, EffectFlags.None, null, null); this.SimpleEffect = new Effect(device, shaderBytes); } catch (Exception e) { System.Diagnostics.Debug.Print(e.Message); throw new Exception("Error compiling: " + shaderPath); } EffectTechnique technique = this.SimpleEffect.GetTechniqueByIndex(0); EffectPass pass = technique.GetPassByIndex(0); this.VertexLayout = new InputLayout(device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) //new InputElement("COLOR", 0, Format.R32G32B32A32_Float, InputElement.AppendAligned, 0) }); int bytesPerVertexInfo = 4 * 8; nrVertices = 4; this.VertexStream = new DataStream(bytesPerVertexInfo * nrVertices, true, true); this.VertexStream.WriteRange(new[] { new Vector4(-1.0f, 1.0f, 0.5f, 1.0f), new Vector4(0.0f, 0.0f, 0.0f, 0.0f), new Vector4(1.0f, -1.0f, 0.5f, 1.0f), new Vector4(1.0f, 1.0f, 0.0f, 0.0f), new Vector4(-1.0f, -1.0f, 0.5f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 0.0f), new Vector4(1.0f, 1.0f, 0.5f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 0.0f) } ); this.VertexStream.Position = 0; this.Vertices = new Buffer(device, this.VertexStream, new BufferDescription() { BindFlags = BindFlags.VertexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = bytesPerVertexInfo * nrVertices, Usage = ResourceUsage.Default } ); nrIndices = 4; int indicesSizeBytes = nrIndices * sizeof(Int32); IndexStream = new DataStream(indicesSizeBytes, true, true); IndexStream.WriteRange <int>(new[] { 3, 1, 0, 2 } ); this.IndexStream.Position = 0; this.Indices = new Buffer(device, this.IndexStream, new BufferDescription() { BindFlags = BindFlags.IndexBuffer, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, SizeInBytes = indicesSizeBytes, Usage = ResourceUsage.Default } ); device.Flush(); }
private void DrawPositionNormalColorIndexedTriangleBuffer(Device device, VertexAndIndexDeviceBuffer deviceBuffers, Matrix worldViewProj) { int layoutNumber = 4; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; if (null != deviceBuffers.ClipPlanes) { for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(deviceBuffers.ClipPlanes[i]); } } SetShaderMaterialVariables(deviceBuffers.Material); device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 48, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); if (null != deviceBuffers.ClipPlanes) { var emptyPlane = new Plane(); for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(emptyPlane); } } }
private void DrawPositionColorLineListBufferNoMaterial(Device device, VertexBufferNoMaterial deviceBuffers, Matrix worldViewProj) { int layoutNumber = 1; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, (8 * 4), 0)); _renderLayouts[layoutNumber].pass.Apply(); device.Draw(deviceBuffers.VertexCount, 0); }
/* public void RenderSoftBodyTextured(SoftBody softBody) { if (!(softBody.UserObject is Array)) return; object[] userObjArr = softBody.UserObject as object[]; FloatArray vertexBuffer = userObjArr[0] as FloatArray; IntArray indexBuffer = userObjArr[1] as IntArray; int vertexCount = (vertexBuffer.Count / 8); if (vertexCount > 0) { int faceCount = indexBuffer.Count / 2; bool index32 = vertexCount > 65536; Mesh mesh = new Mesh(device, faceCount, vertexCount, MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal | VertexFormat.Texture1); SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard); if (index32) { foreach (int i in indexBuffer) indices.Write(i); } else { foreach (int i in indexBuffer) indices.Write((ushort)i); } mesh.UnlockIndexBuffer(); SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard); foreach (float f in vertexBuffer) verts.Write(f); mesh.UnlockVertexBuffer(); mesh.ComputeNormals(); mesh.DrawSubset(0); mesh.Dispose(); } } * */ public static Buffer CreateScreenQuad(Device device) { Buffer vertexBuffer; BufferDescription vertexBufferDesc = new BufferDescription() { SizeInBytes = sizeof(float) * 5 * 4, Usage = ResourceUsage.Default, BindFlags = BindFlags.VertexBuffer, }; using (var data = new DataStream(vertexBufferDesc.SizeInBytes, false, true)) { data.Write(new Vector3(0.5f, 0.5f, 0)); data.Write(new Vector2(1, 0)); data.Write(new Vector3(0.5f, -0.5f, 0)); data.Write(new Vector2(1, 1)); data.Write(new Vector3(-0.5f, 0.5f, 0)); data.Write(new Vector2(0, 0)); data.Write(new Vector3(-0.5f, -0.5f, 0)); data.Write(new Vector2(0, 1)); data.Position = 0; vertexBuffer = new Buffer(device, data, vertexBufferDesc); } return vertexBuffer; }
private void Render() { SharpDX.Direct3D10.Device device = _device; if (device == null) { throw new InvalidOperationException("Rendering failed because 3D device is null"); } Texture2D renderTarget = _renderTargetIntermediate; if (renderTarget == null) { throw new InvalidOperationException("Rendering failed because renderTarget is null"); } int targetWidth = renderTarget.Description.Width; int targetHeight = renderTarget.Description.Height; if (!(targetWidth > 0 && targetHeight > 0)) { throw new InvalidOperationException("Rendering failed because targetWidth or targetHeight is 0"); } device.OutputMerger.SetTargets(_depthStencilView, _renderTargetIntermediateView); device.Rasterizer.SetViewports(new Viewport(0, 0, targetWidth, targetHeight, 0.0f, 1.0f)); device.ClearDepthStencilView(_depthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); if (Scene == null) { device.ClearRenderTargetView(_renderTargetIntermediateView, _renderTargetClearColor); } else // if (this.Scene != null) { if (!_isRenderSceneAttached) { _isRenderSceneAttached = true; _renderScene.Attach(_device, new PointD2D(renderTarget.Description.Width, renderTarget.Description.Height)); } // Attention: it is now the Render function of the scene that is responsible for clearing the render target var renderTargetClearColor = _renderTargetClearColor; var sceneBack = Scene.SceneBackgroundColor; if (sceneBack.HasValue) { renderTargetClearColor = new Color4(sceneBack.Value.ScR, sceneBack.Value.ScG, sceneBack.Value.ScB, sceneBack.Value.ScA); } device.ClearRenderTargetView(_renderTargetIntermediateView, renderTargetClearColor); Scene.Render(); } device.Flush(); // make intermediate render target valid // now start a 2nd stage of rendering, in order to gamma-correct the image // we use the RenderTextureIntermediate that was the target in the first stage now as a ShaderResource in this 2nd stage device.OutputMerger.SetTargets(_renderTargetView); device.Rasterizer.SetViewports(new Viewport(0, 0, targetWidth, targetHeight, 0.0f, 1.0f)); device.ClearRenderTargetView(_renderTargetView, SharpDX.Color.Black); _gammaCorrector.Render(_device, _renderTargetIntermediateShaderResourceView); device.Flush(); // make final render target valid }
public static BasicHlsl.VertexShaderOutput ExecuteVertexShader(string compiledShaderFile, BasicHlsl.ConstantBufferGlobals globals, VertexPositionNormalTexture vertex) { var device = new Device(DriverType.Warp); var vertexShaderBytes = File.ReadAllBytes(compiledShaderFile); var vertexShaderBytecode = new ShaderBytecode(vertexShaderBytes); var vertexShader = new VertexShader(device, vertexShaderBytecode); var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderBytecode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 16, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 28, 0) }); var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { vertex }); var constantBuffer = Buffer.Create(device, ref globals, new BufferDescription { BindFlags = BindFlags.ConstantBuffer, CpuAccessFlags = CpuAccessFlags.None, Usage = ResourceUsage.Default }); var geometryShader = new GeometryShader(device, vertexShaderBytecode, new[] { new StreamOutputElement { SemanticName = "SV_POSITION", ComponentCount = 4 }, new StreamOutputElement { SemanticName = "COLOR", ComponentCount = 4 }, new StreamOutputElement { SemanticName = "TEXCOORD", ComponentCount = 2 } }, BasicHlsl.VertexShaderOutput.SizeInBytes); var outputBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1], new BufferDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.StreamOutput, Usage = ResourceUsage.Default }); var stagingBuffer = Buffer.Create(device, new BasicHlsl.VertexShaderOutput[1], new BufferDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Usage = ResourceUsage.Staging }); device.InputAssembler.InputLayout = layout; device.InputAssembler.PrimitiveTopology = PrimitiveTopology.PointList; device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, VertexPositionNormalTexture.SizeInBytes, 0)); device.VertexShader.SetConstantBuffer(0, constantBuffer); device.VertexShader.Set(vertexShader); device.GeometryShader.Set(geometryShader); device.StreamOutput.SetTargets(new StreamOutputBufferBinding(outputBuffer, 0)); device.Draw(1, 0); device.CopyResource(outputBuffer, stagingBuffer); device.Flush(); var stream = stagingBuffer.Map(MapMode.Read, SharpDX.Direct3D10.MapFlags.None); var bytes = new byte[BasicHlsl.VertexShaderOutput.SizeInBytes]; stream.Read(bytes, 0, bytes.Length); stream.Dispose(); outputBuffer.Dispose(); vertices.Dispose(); layout.Dispose(); geometryShader.Dispose(); vertexShader.Dispose(); vertexShaderBytecode.Dispose(); device.Dispose(); return StructUtility.FromBytes<BasicHlsl.VertexShaderOutput>(bytes); }
public override void Hook() { this.DebugMessage("Hook: Begin"); // Determine method addresses in Direct3D10.Device, and DXGI.SwapChain if (_d3d10VTblAddresses == null) { _d3d10VTblAddresses = new List<IntPtr>(); _dxgiSwapChainVTblAddresses = new List<IntPtr>(); this.DebugMessage("Hook: Before device creation"); using (var factory = new Factory()) { using (var device = new Device(factory.GetAdapter(0), DeviceCreationFlags.None)) { this.DebugMessage("Hook: Device created"); _d3d10VTblAddresses.AddRange(GetVTblAddresses(device.NativePointer, D3D10_DEVICE_METHOD_COUNT)); using (var renderForm = new System.Windows.Forms.Form()) { using (SharpDX.DXGI.SwapChain sc = new SharpDX.DXGI.SwapChain(factory, device, DXGI.CreateSwapChainDescription(renderForm.Handle))) { _dxgiSwapChainVTblAddresses.AddRange(GetVTblAddresses(sc.NativePointer, DXGI.DXGI_SWAPCHAIN_METHOD_COUNT)); } } } } } // We will capture the backbuffer here DXGISwapChain_PresentHook = new Hook<DXGISwapChain_PresentDelegate>( _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.Present], new DXGISwapChain_PresentDelegate(PresentHook), this); // We will capture target/window resizes here DXGISwapChain_ResizeTargetHook = new Hook<DXGISwapChain_ResizeTargetDelegate>( _dxgiSwapChainVTblAddresses[(int)DXGI.DXGISwapChainVTbl.ResizeTarget], new DXGISwapChain_ResizeTargetDelegate(ResizeTargetHook), this); /* * Don't forget that all hooks will start deactivated... * The following ensures that all threads are intercepted: * Note: you must do this for each hook. */ DXGISwapChain_PresentHook.Activate(); DXGISwapChain_ResizeTargetHook.Activate(); Hooks.Add(DXGISwapChain_PresentHook); Hooks.Add(DXGISwapChain_ResizeTargetHook); }
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); } }
private void DrawPositionNormalUIndexedTriangleBuffer(Device device, VertexAndIndexDeviceBuffer deviceBuffers, Matrix worldViewProj) { int layoutNumber = 6; device.InputAssembler.InputLayout = _renderLayouts[layoutNumber].VertexLayout; device.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; // set clip planes if (null != deviceBuffers.ClipPlanes) { for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(deviceBuffers.ClipPlanes[i]); } } // set UColor texture var stream = _textureFor1DColorProvider.Map(0, MapMode.WriteDiscard, SharpDX.Direct3D10.MapFlags.None); //stream.Seek(0, System.IO.SeekOrigin.Begin); stream.Write(deviceBuffers.UColors, 0, deviceBuffers.UColors.Length); //stream.Close(); _textureFor1DColorProvider.Unmap(0); SetShaderMaterialVariables(deviceBuffers.Material); // note: the material's color must be set to the ColorProviders InvalidColor! // draw now device.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(deviceBuffers.VertexBuffer, 32, 0)); device.InputAssembler.SetIndexBuffer(deviceBuffers.IndexBuffer, Format.R32_UInt, 0); _renderLayouts[layoutNumber].pass.Apply(); device.DrawIndexed(deviceBuffers.IndexCount, 0, 0); // clear clip planes afterwards if (null != deviceBuffers.ClipPlanes) { var emptyPlane = new Plane(); for (int i = 0; i < Math.Min(6, deviceBuffers.ClipPlanes.Length); ++i) { _evClipPlanes[i].Set(emptyPlane); } } }